<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Amit Patel on Medium]]></title>
        <description><![CDATA[Stories by Amit Patel on Medium]]></description>
        <link>https://medium.com/@thedev77?source=rss-0098f955eeb7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*l8WZHspvGo5Tc3IS</url>
            <title>Stories by Amit Patel on Medium</title>
            <link>https://medium.com/@thedev77?source=rss-0098f955eeb7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:17:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thedev77/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Implementing Redis-like Caching in PostgreSQL with Node.js]]></title>
            <link>https://thedev77.medium.com/implementing-redis-like-caching-in-postgresql-with-node-js-f57d19fa698a?source=rss-0098f955eeb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f57d19fa698a</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[postgres-over-redis]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Amit Patel]]></dc:creator>
            <pubDate>Tue, 20 Jan 2026 10:23:39 GMT</pubDate>
            <atom:updated>2026-01-20T10:23:39.173Z</atom:updated>
            <content:encoded><![CDATA[<p>As Node.js backend developers, we’re often juggling databases and caches. Here’s a practical way to implement caching directly in PostgreSQL, mimicking Redis commands, using a TypeScript class. This approach leverages your existing Postgres instance, reducing dependencies. We’ll cover the why, schema, code, benchmarks, production tips, and when to choose this over alternatives.</p><p><strong>1.</strong> <strong>Why Postgres Caching vs Redis/Others excels</strong> at in-memory caching with sub-millisecond latencies, but it introduces another service to manage, scale, and secure. Postgres caching makes sense when:</p><ul><li>You already run Postgres as your primary DB — reuse connections and avoid network hops to a separate cache.</li><li>Simplicity trumps raw speed: No extra deployments, backups, or failure points.</li><li>Cost savings: Skip Redis hosting fees (e.g., AWS ElastiCache starts at $45/month).</li><li>Transactional integrity: Cache ops can be atomic with DB writes in one query.</li></ul><p>Compared to Memcached or other in-memory stores, Postgres offers persistence and SQL flexibility, but at a performance trade-off. Use this for moderate loads where 1–10x slower ops are acceptable, especially in integrated workflows where combining cache and DB logic reduces overall latency. 2. Schema Design: Start with a simple table for key-value storage with expiration. Use text for keys and values (stored as JSON strings), and a timestamp for expiry. Make the key the primary key for uniqueness and fast lookups.</p><p>sql</p><pre>CREATE TABLE cache (<br>  key text PRIMARY KEY,<br>  value text NOT NULL,<br>  expires_at timestamp with time zone NOT NULL<br>);</pre><ul><li>key: Unique identifier (e.g., ‘user:123:profile’).</li><li>value: JSON-stringified data.</li><li>expires_at: Auto-handles TTL; queries filter on NOW() &gt; expires_at.</li></ul><p>For better performance, consider jsonb for value if you need querying inside values:</p><p>sql</p><pre>ALTER TABLE cache ALTER COLUMN value TYPE jsonb USING value::jsonb;</pre><p>But stick to text if parsing in app code is fine — it avoids Postgres JSON overhead. Add an index on expires_at for efficient cleanups:</p><p>sql</p><pre>CREATE INDEX idx_cache_expires_at ON cache (expires_at);</pre><p>Use unlogged tables for faster writes if durability isn’t critical (cache data is disposable):</p><p>sql</p><pre>CREATE UNLOGGED TABLE cache (...);</pre><p>3. Code Walkthrough: The PgCache class wraps Postgres queries to mimic Redis patterns. It uses a Pool from pg for connections (imported as pool). Focus on set/get/mget; other methods like del, exists, ttl, flushAll, and cleanup follow similar SQL patterns. Setup</p><p>typescript</p><pre>import { pool } from &#39;./db.js&#39;;  // Your pg Pool instance</pre><p>Set a Key with TTLInserts or updates with conflict handling. TTL in seconds; note: the code uses ‘1 hour’ — fix to ‘1 second’ for accuracy.</p><p>typescript</p><pre>static async set&lt;T&gt;(key: string, value: T, ttlSeconds: number): Promise&lt;void&gt; {<br>  await pool.query(<br>    `INSERT INTO cache (key, value, expires_at)<br>     VALUES ($1, $2, NOW() + ($3 * INTERVAL &#39;1 second&#39;))<br>     ON CONFLICT (key) DO UPDATE<br>     SET value = EXCLUDED.value,<br>         expires_at = EXCLUDED.expires_at`,<br>    [key, JSON.stringify(value), ttlSeconds]<br>  );<br>}</pre><p><strong>Get a KeyFilters expired entries; parses JSON.</strong></p><p>typescript</p><pre>static async get&lt;T&gt;(key: string): Promise&lt;T | null&gt; {<br>  const { rows } = await pool.query(<br>    `SELECT value<br>     FROM cache<br>     WHERE key = $1<br>     AND expires_at &gt; NOW()`,<br>    [key]<br>  );</pre><pre>  if (rows.length === 0) return null;<br>  <br>  try {<br>    return JSON.parse(rows[0].value) as T;<br>  } catch (error) {<br>    console.error(&#39;Error parsing cached value:&#39;, error);<br>    return null;<br>  }<br>}</pre><p><strong>Multi-Get (mget)Batch fetches non-expired keys; maps results.</strong></p><p>typescript</p><pre>static async mget&lt;T&gt;(keys: string[]): Promise&lt;(T | null)[]&gt; {<br>  if (keys.length === 0) return [];</pre><pre>  const placeholders = keys.map((_, index) =&gt; `$${index + 1}`).join(&#39;,&#39;);<br>  const { rows } = await pool.query(<br>    `SELECT key, value<br>     FROM cache<br>     WHERE key IN (${placeholders})<br>     AND expires_at &gt; NOW()`,<br>    keys<br>  );</pre><pre>  const resultMap = new Map&lt;string, T&gt;();<br>  rows.forEach(row =&gt; {<br>    try {<br>      resultMap.set(row.key, JSON.parse(row.value));<br>    } catch (error) {<br>      console.error(`Error parsing cached value for key ${row.key}:`, error);<br>    }<br>  });</pre><pre>  return keys.map(key =&gt; resultMap.get(key) || null);<br>}</pre><p><strong>Multi-Set (mset)Batch inserts/updates with shared TTL.</strong></p><p>typescript</p><pre>static async mset&lt;T&gt;(entries: Array&lt;{ key: string; value: T }&gt;, ttlSeconds: number): Promise&lt;void&gt; {<br>  if (entries.length === 0) return;</pre><pre>  const values: any[] = [];<br>  const placeholders: string[] = [];<br>  <br>  entries.forEach((entry, index) =&gt; {<br>    const baseIndex = index * 3;<br>    placeholders.push(`($${baseIndex + 1}, $${baseIndex + 2}, NOW() + ($${baseIndex + 3} * INTERVAL &#39;1 second&#39;))`);<br>    values.push(entry.key, JSON.stringify(entry.value), ttlSeconds);<br>  });</pre><pre>  await pool.query(<br>    `INSERT INTO cache (key, value, expires_at)<br>     VALUES ${placeholders.join(&#39;, &#39;)}<br>     ON CONFLICT (key) DO UPDATE<br>     SET value = EXCLUDED.value,<br>         expires_at = EXCLUDED.expires_at`,<br>    values<br>  );<br>}</pre><p>Usage example:</p><p>typescript</p><pre>await PgCache.set(&#39;user:1&#39;, { name: &#39;Alice&#39; }, 3600);<br>const user = await PgCache.get&lt;{ name: string }&gt;(&#39;user:1&#39;);<br>const users = await PgCache.mget&lt;{ name: string }&gt;([&#39;user:1&#39;, &#39;user:2&#39;]);</pre><p><strong>4. Performance Benchmarks vs Native RedisBenchmarks</strong> vary by setup (e.g., local vs remote, tuned configs). From real-world tests (AWS RDS, single instance, 1M entries):</p><p><strong>Operation</strong></p><p>Redis (ms)</p><p>Postgres (ms)</p><p>Throughput (ops/sec) Redis</p><p>Throughput (ops/sec) Postgres</p><p><strong>SET</strong></p><p>0.05–0.10</p><p>0.08–2.0</p><p>100k+</p><p>10k-50k</p><p><strong>GET</strong></p><p>0.04–0.10</p><p>0.06–1.0</p><p>100k+</p><p>10k-50k</p><p><strong>MGET (10 keys)</strong></p><p>~0.10</p><p>~0.20</p><p>50k+</p><p>5k-20k</p><p>Sources: Benchmarks show Redis 2–10x faster for isolated ops due to in-memory design</p><p>medium.com +2</p><p>. Postgres shines in combined DB+cache workflows (e.g., atomic insert + cache set in one transaction: ~2ms vs Redis’s 4ms with hops). Untuned Postgres hits 7k-15k RPS; tune with unlogged tables for 20k+ writes/sec. For high-scale, Redis wins; for integrated Node.js apps, Postgres is “fast enough” without extra latency.5. Production Considerations</p><ul><li>Indexing: Primary key on key handles lookups. Index expires_at for fast deletions.</li><li>Cleanup Cron: Schedule PgCache.cleanup() every 5–15 mins via Node cron (cron package). It deletes expired rows efficiently.</li><li>typescript</li><li>import cron from &#39;node-cron&#39;; cron.schedule(&#39;*/5 * * * *&#39;, async () =&gt; { const deleted = await PgCache.cleanup(); console.log(`Cleaned ${deleted} expired keys`); });</li><li>Connection Pooling: Reuse pool to avoid overhead. Monitor query times with pg_stat_statements.</li><li>Eviction: No built-in LRU; implement via triggers or app logic if needed.</li><li>Scaling: Partition table by key hash for large caches. Use read replicas for gets.</li><li>Error Handling: Wrap parses in try-catch; log failures.</li><li>Durability: Unlogged tables speed writes but risk data loss on crash — fine for caches.</li><li>Monitoring: Track table size (pg_relation_size), hit rates in app logs.</li></ul><p><strong>6. When to Use This vs Alternatives: Use Postgres caching when:</strong></p><ul><li>Traffic is low-moderate (&lt;10k cache ops/sec).</li><li>You want one less service (no Redis deploy/HA).</li><li>Need atomicity with DB (e.g., cache invalidate on update).</li><li>Cost/simplicity priority over peak perf.</li></ul><p>Switch to Redis/Memcached when:</p><ul><li>Sub-ms latency critical (e.g., high-traffic APIs).</li><li>Advanced features needed (pub/sub, sorted sets).</li><li>Cache size exceeds Postgres RAM allocation.</li><li>Independent scaling required.</li></ul><p>For Node.js, start here if Postgres is underutilised — profile, then migrate if bottlenecks appear.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f57d19fa698a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Transfer Proxy Contract Ownership from Biconomy Smart Account to EOA]]></title>
            <link>https://thedev77.medium.com/how-to-transfer-proxy-contract-ownership-from-biconomy-smart-account-to-eoa-5dc0ec10b3e8?source=rss-0098f955eeb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dc0ec10b3e8</guid>
            <category><![CDATA[smart-accounts]]></category>
            <category><![CDATA[biconomy]]></category>
            <category><![CDATA[proxy-contract]]></category>
            <dc:creator><![CDATA[Amit Patel]]></dc:creator>
            <pubDate>Fri, 05 Dec 2025 07:50:59 GMT</pubDate>
            <atom:updated>2025-12-05T07:55:23.168Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*noM-6kflfB3JGfKtUMUiKw.png" /></figure><h3><strong>Introduction</strong></h3><p>When building decentralised applications with account abstraction, you might need to transfer ownership of your proxy contracts from a Biconomy Smart Account to an Externally Owned Account (EOA) like a Privy wallet. This is a common scenario when transitioning from gasless transactions to traditional wallet management, or when you need to change the primary signer of your smart contracts.</p><p>In this guide, we’ll walk through a secure three-step process to transfer ownership while maintaining security best practices.</p><p><strong>Prerequisites</strong></p><p>Before we begin, make sure you have:</p><p>- Node.js and npm installed</p><p>- A Biconomy Smart Account with ownership of a proxy contract</p><p>- A new EOA wallet (e.g., Privy wallet) to receive ownership</p><p>- Access to Biconomy bundler and paymaster services</p><p>- The proxy contract ABI</p><p><strong>Required Dependencies</strong></p><pre>npm install @biconomy/abstractjs viem ethers axios</pre><p><strong>Setup and Configuration</strong></p><p>First, let’s set up our environment with the necessary imports and configuration:</p><pre>import { createBicoPaymasterClient, createSmartAccountClient, toNexusAccount } from &#39;@biconomy/abstractjs&#39;;<br>import { privateKeyToAccount } from &#39;viem/accounts&#39;;<br>import { createPublicClient, http, encodeFunctionData } from &#39;viem&#39;;<br>import { baseSepolia } from &#39;viem/chains&#39;;<br>import { Contract, ethers } from &#39;ethers&#39;;<br>import ProxyContractAbi from &#39;./ownerShipAbi.json&#39;;<br><br>// Configuration<br>const bundlerUrl = &#39;https://bundler.biconomy.io/api/v3/84532/YOUR_BUNDLER_KEY&#39;;<br>const paymasterUrl = &#39;https://paymaster.biconomy.io/api/v2/84532/YOUR_PAYMASTER_KEY&#39;;<br>const rpcUrl = &#39;https://base-sepolia.infura.io/v3/YOUR_INFURA_KEY&#39;;</pre><p><strong>Understanding the Ownership Transfer Process</strong></p><p>The ownership transfer involves three critical steps:</p><p><strong>1. Add New Admin:</strong> Add the new EOA (Privy wallet) as an admin to the proxy contract</p><p><strong>2. Transfer Ownership:</strong> Transfer primary ownership to the new admin</p><p><strong>3. Remove Old Admin:</strong> Remove the Biconomy wallet as admin (security best practice)</p><p>Let’s implement each step.</p><h3><strong>Step 1: Create Biconomy Smart Account Client</strong></h3><p>Before we can perform any operations, we need to create a Biconomy Smart Account client:</p><pre>async function createSmartAccount() {<br>    // Your Biconomy Smart Account private key<br>    const privateKey = &quot;0xYOUR_BICONOMY_PRIVATE_KEY&quot;;<br>    <br>    const account = privateKeyToAccount(privateKey);<br>    <br>    const nexusClient = createSmartAccountClient({<br>        account: await toNexusAccount({<br>            signer: account,<br>            chain: baseSepolia,<br>            transport: http(rpcUrl),<br>        }),<br>        transport: http(bundlerUrl),<br>        paymaster: createBicoPaymasterClient({ paymasterUrl }),<br>    });<br><br>    console.log(&quot;Smart Account Address:&quot;, nexusClient.account.address);<br>    return nexusClient;<br>}</pre><h3><strong>Step 2: Add New Admin (EOA Wallet)</strong></h3><p>The first step is to add your new EOA wallet as an admin to the proxy contract. This is done using the Biconomy Smart Account as the signer:</p><pre>async function addOwner(newAdminAddress: string, proxyAddress: string) {<br>    try {<br>        const nexusClient = await createSmartAccount();<br>        <br>        // Send user operation to add new admin<br>        const hash = await nexusClient.sendUserOperation({<br>            calls: [<br>                {<br>                    to: proxyAddress as `0x${string}`,<br>                    abi: ProxyContractAbi,<br>                    value: BigInt(0),<br>                    functionName: &quot;addAdmin&quot;,<br>                    args: [newAdminAddress as `0x${string}`]<br>                }<br>            ]<br>        });<br>        <br>        console.log(&quot;Transaction Hash:&quot;, hash);<br>        <br>        // Wait for transaction confirmation<br>        const receipt = await nexusClient.waitForUserOperationReceipt({ hash });<br>        console.log(&quot;Transaction Receipt:&quot;, receipt);<br>        <br>        return receipt;<br>    } catch (error) {<br>        console.error(&quot;Error adding admin:&quot;, error);<br>        throw error;<br>    }<br>}<br><br>// Usage<br>await addOwner(<br>    &quot;0xYOUR_PRIVY_WALLET_ADDRESS&quot;,<br>    &quot;0xYOUR_PROXY_CONTRACT_ADDRESS&quot;<br>);</pre><h4>What’s happening here?</h4><p>- We use the Biconomy Smart Account to call the `<strong>addAdmin</strong>` function</p><p>- The transaction is gasless (sponsored by the paymaster)</p><p>- The new EOA is now added as an admin alongside the Biconomy wallet</p><h3><strong>Step 3: Transfer Ownership</strong></h3><p>Now that the new wallet is an admin, we can transfer primary ownership:</p><pre>async function transferOwner(newOwnerAddress: string, proxyAddress: string) {<br>    try {<br>        const nexusClient = await createSmartAccount();<br>        <br>        // Send user operation to transfer ownership<br>        const hash = await nexusClient.sendUserOperation({<br>            calls: [<br>                {<br>                    to: proxyAddress as `0x${string}`,<br>                    abi: ProxyContractAbi,<br>                    value: BigInt(0),<br>                    functionName: &quot;transferOwnership&quot;,<br>                    args: [newOwnerAddress as `0x${string}`]<br>                }<br>            ]<br>        });<br>        <br>        console.log(&quot;Transfer Hash:&quot;, hash);<br>        <br>        const receipt = await nexusClient.waitForUserOperationReceipt({ hash });<br>        console.log(&quot;Transfer Receipt:&quot;, receipt);<br>        <br>        return receipt;<br>    } catch (error) {<br>        console.error(&quot;Error transferring ownership:&quot;, error);<br>        throw error;<br>    }<br>}<br><br>// Usage<br>await transferOwner(<br>    &quot;0xYOUR_PRIVY_WALLET_ADDRESS&quot;,<br>    &quot;0xYOUR_PROXY_CONTRACT_ADDRESS&quot;<br>);</pre><h4>Important Notes:</h4><p>- The Biconomy wallet still has admin privileges at this point</p><p>- The new EOA is now the primary owner</p><p>- This is still a gasless transaction</p><h3><strong>Step 4: Remove Old Admin (Security Best Practice)</strong></h3><p>Finally, we remove the Biconomy wallet as an admin. This step is crucial for security:</p><pre>async function removeAdminByNewOwner(oldAdminAddress: string, proxyAddress: string) {<br>    try {<br>        // Now we use the NEW owner&#39;s private key (Privy wallet)<br>        const newOwnerPrivateKey = &quot;0xYOUR_PRIVY_WALLET_PRIVATE_KEY&quot;;<br>        <br>        const provider = new ethers.JsonRpcProvider(rpcUrl);<br>        const wallet = new ethers.Wallet(newOwnerPrivateKey, provider);<br>        <br>        console.log(&quot;Signer Address:&quot;, await wallet.getAddress());<br>        <br>        // Create contract instance<br>        const proxyContract = new ethers.Contract(<br>            proxyAddress,<br>            ProxyContractAbi,<br>            wallet<br>        );<br>        <br>        // Remove the old Biconomy admin<br>        const tx = await proxyContract.removeAdmin(oldAdminAddress);<br>        console.log(&quot;Transaction Hash:&quot;, tx.hash);<br>        <br>        // Wait for confirmation<br>        const receipt = await tx.wait();<br>        console.log(&quot;Transaction Mined:&quot;, receipt);<br>        <br>        return receipt;<br>    } catch (error) {<br>        console.error(&quot;Error removing admin:&quot;, error);<br>        throw error;<br>    }<br>}<br><br>// Usage<br>await removeAdminByNewOwner(<br>    &quot;0xBICONOMY_SMART_ACCOUNT_ADDRESS&quot;,<br>    &quot;0xYOUR_PROXY_CONTRACT_ADDRESS&quot;<br>);</pre><p>Or if you are using the viem npm package</p><pre>import { createWalletClient, createPublicClient, http } from &quot;viem&quot;;<br>import { privateKeyToAccount } from &quot;viem/accounts&quot;;<br>import { baseSepolia } from &quot;viem/chains&quot;; // ⬅️ change to your actual chain<br>import type { Address, Hash } from &quot;viem&quot;;<br>// import ProxyContractAbi from &quot;./abis/ProxyContractAbi.json&quot;;<br><br>const rpcUrl = &quot;https://your-rpc-url&quot;; // ⬅️ set this<br><br>async function removeAdminByNewOwner(<br>  oldAdminAddress: Address,<br>  proxyAddress: Address<br>) {<br>  try {<br>    // Now we use the NEW owner&#39;s private key (Privy wallet)<br>    const newOwnerPrivateKey = &quot;0xYOUR_PRIVY_WALLET_PRIVATE_KEY&quot; as `0x${string}`;<br><br>    const account = privateKeyToAccount(newOwnerPrivateKey);<br><br>    // wallet client (for sending tx)<br>    const walletClient = createWalletClient({<br>      account,<br>      chain: baseSepolia, // ⬅️ change chain if needed<br>      transport: http(rpcUrl),<br>    });<br><br>    // public client (for waiting on receipt)<br>    const publicClient = createPublicClient({<br>      chain: baseSepolia,<br>      transport: http(rpcUrl),<br>    });<br><br>    console.log(&quot;Signer Address:&quot;, account.address);<br><br>    // writeContract = send tx<br>    const hash: Hash = await walletClient.writeContract({<br>      address: proxyAddress,<br>      abi: ProxyContractAbi,<br>      functionName: &quot;removeAdmin&quot;,<br>      args: [oldAdminAddress],<br>    });<br><br>    console.log(&quot;Transaction Hash:&quot;, hash);<br><br>    // wait for confirmation<br>    const receipt = await publicClient.waitForTransactionReceipt({ hash });<br><br>    console.log(&quot;Transaction Mined:&quot;, receipt);<br><br>    return receipt;<br>  } catch (error) {<br>    console.error(&quot;Error removing admin:&quot;, error);<br>    throw error;<br>  }<br>}<br><br>// Usage<br>await removeAdminByNewOwner(<br>  &quot;0xBICONOMY_SMART_ACCOUNT_ADDRESS&quot; as Address,<br>  &quot;0xYOUR_PROXY_CONTRACT_ADDRESS&quot; as Address<br>);</pre><p><strong>Key Differences:</strong></p><p>- This transaction is signed by the NEW owner (EOA wallet)</p><p>- This is NOT a gasless transaction — you’ll need ETH for gas</p><ul><li>After this step, only the new EOA has control</li></ul><p><strong>Verification: Check Admin Status</strong></p><p>It’s important to verify each step. Here’s how to check if an address is an admin:</p><pre>import { ethers } from &quot;ethers&quot;;<br>// import ProxyContractAbi from &quot;./ProxyContractAbi.json&quot;;<br><br>const provider = new ethers.JsonRpcProvider(rpcUrl);<br><br>async function isAdmin(proxyContractAddress: string, addressToCheck: string) {<br>    try {<br>        // Create read-only contract instance<br>        const contract = new ethers.Contract(<br>            proxyContractAddress,<br>            ProxyContractAbi,<br>            provider<br>        );<br><br>        // Call view function<br>        const result = await contract.isAdmin(addressToCheck);<br><br>        console.log(`Is ${addressToCheck} an admin?`, result);<br>        return result;<br>    } catch (error) {<br>        console.error(&quot;Error checking admin status:&quot;, error);<br>        throw error;<br>    }<br>}<br><br>// Usage Example<br>await isAdmin(<br>    &quot;0xYOUR_PROXY_CONTRACT_ADDRESS&quot;,<br>    &quot;0xYOUR_PRIVY_WALLET_ADDRESS&quot;<br>);</pre><p>If you are using the viem npm package</p><pre>async function isAdmin(proxyContractAddress: string, addressToCheck: string) {<br>    try {<br>        const publicClient = createPublicClient({<br>            chain: baseSepolia,<br>            transport: http(rpcUrl),<br>        });<br>        <br>        const result = await publicClient.readContract({<br>            address: proxyContractAddress as `0x${string}`,<br>            abi: ProxyContractAbi,<br>            functionName: &quot;isAdmin&quot;,<br>            args: [addressToCheck as `0x${string}`]<br>        });<br><br>        console.log(`Is ${addressToCheck} an admin?`, result);<br>        return result;<br>    } catch (error) {<br>        console.error(&quot;Error checking admin status:&quot;, error);<br>        throw error;<br>    }<br>}<br><br>// Verify the new owner<br>await isAdmin(<br>    &quot;0xYOUR_PROXY_CONTRACT_ADDRESS&quot;,<br>    &quot;0xYOUR_PRIVY_WALLET_ADDRESS&quot;<br>);</pre><h3><strong>Complete Workflow Example</strong></h3><p>Here’s how to execute the entire process:</p><pre>async function completeOwnershipTransfer() {<br>    const proxyAddress = &quot;0xYOUR_PROXY_CONTRACT_ADDRESS&quot;;<br>    const newOwnerAddress = &quot;0xYOUR_PRIVY_WALLET_ADDRESS&quot;;<br>    const biconomyAddress = &quot;0xBICONOMY_SMART_ACCOUNT_ADDRESS&quot;;<br>    <br>    try {<br>        console.log(&quot;Step 1: Adding new admin...&quot;);<br>        await addOwner(newOwnerAddress, proxyAddress);<br>        console.log(&quot;✓ New admin added successfully\n&quot;);<br>        <br>        // Verify<br>        await isAdmin(proxyAddress, newOwnerAddress);<br>        <br>        console.log(&quot;Step 2: Transferring ownership...&quot;);<br>        await transferOwner(newOwnerAddress, proxyAddress);<br>        console.log(&quot;✓ Ownership transferred successfully\n&quot;);<br>        <br>        console.log(&quot;Step 3: Removing old admin...&quot;);<br>        await removeAdminByNewOwner(biconomyAddress, proxyAddress);<br>        console.log(&quot;✓ Old admin removed successfully\n&quot;);<br>        <br>        // Final verification<br>        console.log(&quot;Final verification:&quot;);<br>        await isAdmin(proxyAddress, newOwnerAddress);<br>        await isAdmin(proxyAddress, biconomyAddress);<br>        <br>        console.log(&quot;✓ Ownership transfer complete!&quot;);<br>    } catch (error) {<br>        console.error(&quot;Ownership transfer failed:&quot;, error);<br>    }<br>}<br><br>// Execute the transfer<br>completeOwnershipTransfer();</pre><p><strong>Security Considerations</strong></p><p><strong>Why Remove the Old Admin?</strong></p><p>Removing the old Biconomy admin is crucial for security:</p><p><strong>1. Single Point of Control:</strong> Ensures only the new owner has control</p><p><strong>2. Prevents Unauthorised Access:</strong> The old private key can’t be used to modify the contract</p><p><strong>3. Clear Ownership: </strong>Makes it explicit who controls the contract</p><p><strong>4. Audit Trail:</strong> Shows a clean transition of ownership</p><p><strong>Best Practices</strong></p><p>- <strong>Backup Private Keys</strong>: Ensure you have secure backups of the new owner’s private key</p><p>- <strong>Test on Testnet</strong>: Always test the entire process on a testnet first</p><p>- <strong>Verify Each Step</strong>: Check admin status after each operation</p><p>- <strong>Gas Funds</strong>: Ensure the new EOA has sufficient ETH for the final transaction</p><p>- <strong>Time Locks</strong>: Consider implementing time locks for critical operations</p><p>- <strong>Multi-Sig</strong>: For production, consider using a multi-sig wallet as the new owner</p><p><strong>Common Issues and Troubleshooting</strong></p><p><strong>Issue 1: “Not authorised” error in Step 1 or 2</strong></p><p><strong>Solution:</strong> Ensure the Biconomy Smart Account is the current owner/admin</p><p><strong>Issue 2: “Insufficient funds” in Step 3</strong></p><p><strong>Solution:</strong> The new EOA needs ETH for gas. Fund it before removing the old admin</p><p><strong>Issue 3: Transaction reverts during removeAdmin</strong></p><p><strong>Solution:</strong> Verify the new owner has been properly set and has the authority to remove admins</p><p><strong>Issue 4: Paymaster rejection</strong></p><p><strong>Solution:</strong> Check your paymaster configuration and ensure you have sufficient credits</p><h3><strong>Alternative: Skip Step 3?</strong></h3><p>You might wonder: “Do I really need to remove the old admin?”</p><p><strong>Short answer: </strong>Yes, for security.</p><p><strong>Long answer:</strong> While technically the contract will function with multiple admins, keeping the old Biconomy admin creates security risks:</p><p>- If the Biconomy private key is compromised, attackers can still control your contract</p><p>- It creates ambiguity about who truly owns the contract</p><p>- It violates the principle of least privilege</p><p>However, there are scenarios where you might keep both:</p><p>- During a transition period for testing</p><p>- If you want to maintain gasless transaction capabilities</p><p>- If you’re using a multi-admin governance model</p><h3><strong>Conclusion</strong></h3><p>Transferring ownership from a Biconomy Smart Account to an EOA is a straightforward but critical process. By following these three steps — adding the new admin, transferring ownership, and removing the old admin — you ensure a secure and complete transition of control.</p><p>Remember:</p><p>- Steps 1 and 2 use the Biconomy Smart Account (gasless)</p><p>- Step 3 uses the new EOA (requires gas)</p><p>- Always verify each step before proceeding</p><p>- Test thoroughly on testnet before production</p><p>The code examples provide are production-ready and can be adapted to your specific use case. Happy building!</p><h3><strong>Additional Resources</strong></h3><p>- Biconomy Documentation [<a href="https://docs.biconomy.io/"><em>Link</em></a>]</p><p>- Viem Documentation[<a href="https://viem.sh/"><em>Link</em></a>]</p><p>- Ethers.js Documentation[<a href="https://docs.ethers.org/"><em>Link</em></a>]</p><p>- Account Abstraction (ERC-4337)[<a href="https://eips.ethereum.org/EIPS/eip-4337"><em>Link</em></a>]</p><p>— -</p><p><em>*Have questions or run into issues? Feel free to reach out in the comments below!* <br>Or Connect on </em><a href="https://x.com/TheDev77"><em>Twitter</em></a><em>, </em><a href="https://www.linkedin.com/in/amitpatel2001/"><em>LinkedIn</em></a><em> and </em><a href="https://t.me/TheDev77"><em>Telegram</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dc0ec10b3e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive into Privy Integration in React or React Native CLI (Web view)]]></title>
            <link>https://thedev77.medium.com/deep-dive-into-privy-integration-in-react-or-react-native-cli-web-view-1c9d6de0dd10?source=rss-0098f955eeb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c9d6de0dd10</guid>
            <category><![CDATA[wallet]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[privy]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Amit Patel]]></dc:creator>
            <pubDate>Thu, 13 Nov 2025 10:05:52 GMT</pubDate>
            <atom:updated>2025-11-13T10:05:52.869Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Table of Contents</strong></h3><p>1. Introduction</p><p>2. What is Privy?</p><p>3. Setup and Installation</p><p>4. Core Concepts</p><p>5. Authentication Methods</p><p>6. Wallet Management</p><p>7. Advanced Features</p><p>8. React Native Integration</p><p>9. Best Practices</p><p>10. Common Pitfalls</p><h3><strong>Introduction</strong></h3><p>Privy is a powerful authentication and wallet management solution designed specifically for Web3 applications. It bridges the gap between traditional Web2 authentication methods and Web3 wallet functionality, making it easier to onboard mainstream users into decentralised applications.</p><p>This guide provides a comprehensive walkthrough of integrating Privy into React and React Native applications, with practical code examples and real-world use cases.</p><h3><strong>What is Privy?</strong></h3><p>Privy offers:</p><ul><li><strong>Multiple Authentication Methods</strong>: Email, SMS, social logins, passkeys, and wallet connections</li><li><strong>Embedded Wallets:</strong> Automatically created wallets for users without crypto experience</li><li><strong>Cross-Chain Support:</strong> Ethereum, Solana, and other blockchain networks</li><li><strong>Secure Key Management:</strong> MPC (Multi-Party Computation) for enhanced security</li><li><strong>Seamless UX:</strong> No seed phrases or complex wallet setup for end users</li></ul><h3><strong>Setup and Installation</strong></h3><p><strong>Prerequisites</strong></p><pre>node &gt;= 16.x<br>npm or yarn or pnpm</pre><p><strong>Installation</strong></p><p>For React Web Applications</p><pre>npm install @privy-io/react-auth<br># or<br>yarn add @privy-io/react-auth<br># or<br>pnpm add @privy-io/react-auth</pre><p><strong>For Solana Support</strong></p><pre>npm install @privy-io/react-auth @privy-io/react-auth/solana</pre><p><strong>Additional Dependencies</strong></p><pre>npm install @solana/kit @solana-program/system bs58<br><br># For styling (optional)<br>npm install tailwindcss</pre><p><strong>Environment Setup</strong></p><p>Create a `.env` file in your project root:</p><pre>VITE_PRIVY_APP_ID=your_privy_app_id_here</pre><p>Get your App ID from the <a href="https://dashboard.privy.io/"><em>Privy Dashboard</em></a></p><h3><strong>Core Concepts</strong></h3><p><strong>1. PrivyProvider Setup</strong></p><p>The `<em>PrivyProvider</em>` wraps your application and provides an authentication context.</p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom/client&#39;;<br>import { PrivyProvider } from &#39;@privy-io/react-auth&#39;;<br>import App from &#39;./App&#39;;<br>import &#39;./index.css&#39;;<br><br>ReactDOM.createRoot(document.getElementById(&#39;root&#39;)!).render(<br>  &lt;React.StrictMode&gt;<br>    &lt;PrivyProvider<br>      appId={import.meta.env.VITE_PRIVY_APP_ID}<br>      config={{<br>        // Appearance customization<br>        appearance: {<br>          theme: &#39;dark&#39;,<br>          accentColor: &#39;#6366f1&#39;,<br>          logo: &#39;https://your-logo-url.com/logo.png&#39;,<br>        },<br>        // Login methods<br>        loginMethods: [&#39;email&#39;, &#39;wallet&#39;, &#39;google&#39;, &#39;twitter&#39;, &#39;discord&#39;, &#39;passkey&#39;],<br>        // Embedded wallet configuration<br>        embeddedWallets: {<br>          createOnLogin: &#39;users-without-wallets&#39;,<br>          requireUserPasswordOnCreate: false,<br>        },<br>        // Supported chains<br>        supportedChains: [<br>          { id: 1, name: &#39;Ethereum&#39; },<br>          { id: 137, name: &#39;Polygon&#39; },<br>          { id: 8453, name: &#39;Base&#39; },<br>        ],<br>        // Solana support<br>        solana: {<br>          cluster: &#39;devnet&#39;, // or &#39;mainnet-beta&#39;<br>        },<br>      }}<br>    &gt;<br>      &lt;App /&gt;<br>    &lt;/PrivyProvider&gt;<br>  &lt;/React.StrictMode&gt;<br>);</pre><p><strong>2. Key Hooks Overview</strong></p><p><strong>| Hook | Purpose |</strong></p><p>| — — — | — — — — -|</p><p>| `<strong>usePrivy()</strong>` | Core authentication state and methods |</p><p>| `<strong>useWallets()</strong>` | Access EVM wallets |</p><p>| `<strong>useWallets()</strong>` (Solana) | Access Solana wallets |</p><p>| `<strong>useLoginWithPasskey()</strong>` | Passkey authentication |</p><p>| `<strong>useCreateWallet()</strong>` | Create new embedded wallets |</p><p>| `<strong>useSignMessage()</strong>` | Sign messages |</p><p>| `<strong>useSendTransaction()</strong>` | Send blockchain transactions |</p><h3><strong>Authentication Methods</strong></h3><p><strong>Basic Login/Logout</strong></p><pre>import { usePrivy } from &#39;@privy-io/react-auth&#39;;<br><br>function AuthComponent() {<br>  const { login, logout, authenticated, user } = usePrivy();<br><br>  return (<br>    &lt;div&gt;<br>      {!authenticated ? (<br>        &lt;button onClick={login}&gt;Login&lt;/button&gt;<br>      ) : (<br>        &lt;&gt;<br>          &lt;p&gt;Welcome, {user?.id}&lt;/p&gt;<br>          &lt;button onClick={logout}&gt;Logout&lt;/button&gt;<br>        &lt;/&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}</pre><h4><strong>Passkey Authentication</strong></h4><p>Passkeys provide passwordless, phishing-resistant authentication using WebAuthn.</p><p><strong>Sign up with Passkey</strong></p><pre>import { useSignupWithPasskey } from &#39;@privy-io/react-auth&#39;;<br><br>function PasskeySignup() {<br>  const { signupWithPasskey } = useSignupWithPasskey({<br>    onComplete: (user) =&gt; {<br>      console.log(&#39;User signed up:&#39;, user);<br>      // Automatically create wallet after signup<br>      createWallet();<br>    },<br>    onError: (error) =&gt; {<br>      console.error(&#39;Signup failed:&#39;, error);<br>      alert(&#39;Failed to sign up with passkey&#39;);<br>    }<br>  });<br><br>  return (<br>    &lt;button onClick={() =&gt; signupWithPasskey()}&gt;<br>      Sign Up with Passkey<br>    &lt;/button&gt;<br>  );<br>}</pre><p><strong>Login with Passkey</strong></p><pre>import { useLoginWithPasskey } from &#39;@privy-io/react-auth&#39;;<br><br>function PasskeyLogin() {<br>  const { loginWithPasskey } = useLoginWithPasskey({<br>    onComplete: (user) =&gt; {<br>      console.log(&#39;User logged in:&#39;, user);<br>    },<br>    onError: (error) =&gt; {<br>      console.error(&#39;Login failed:&#39;, error);<br>    }<br>  });<br><br>  return (<br>    &lt;button onClick={() =&gt; loginWithPasskey()}&gt;<br>      Login with Passkey<br>    &lt;/button&gt;<br>  );<br>}</pre><p><strong>Link Additional Passkey</strong></p><pre>import { useLinkWithPasskey } from &#39;@privy-io/react-auth&#39;;<br><br>function LinkPasskey() {<br>  const { linkWithPasskey } = useLinkWithPasskey({<br>    onSuccess: (user) =&gt; {<br>      console.log(&#39;Passkey linked:&#39;, user);<br>      alert(&#39;Passkey linked successfully!&#39;);<br>    },<br>    onError: (error) =&gt; {<br>      console.error(&#39;Failed to link passkey:&#39;, error);<br>    }<br>  });<br><br>  return (<br>    &lt;button onClick={() =&gt; linkWithPasskey()}&gt;<br>      Link New Passkey<br>    &lt;/button&gt;<br>  );<br>}</pre><p><strong>Unlink Passkey</strong></p><pre>import { usePrivy } from &#39;@privy-io/react-auth&#39;;<br>import { useState } from &#39;react&#39;;<br><br>function UnlinkPasskey() {<br>  const { user, unlinkPasskey } = usePrivy();<br>  const [selectedPasskeyId, setSelectedPasskeyId] = useState(&#39;&#39;);<br><br>  // Get all passkey accounts<br>  const passkeyAccounts = user?.linkedAccounts.filter(<br>    (account) =&gt; account.type === &#39;passkey&#39;<br>  ) || [];<br><br>  const handleUnlink = async () =&gt; {<br>    if (!selectedPasskeyId) {<br>      alert(&#39;Please select a passkey&#39;);<br>      return;<br>    }<br><br>    try {<br>      await unlinkPasskey(selectedPasskeyId);<br>      alert(&#39;Passkey unlinked successfully!&#39;);<br>      setSelectedPasskeyId(&#39;&#39;);<br>    } catch (error) {<br>      console.error(&#39;Failed to unlink:&#39;, error);<br>    }<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;select <br>        value={selectedPasskeyId}<br>        onChange={(e) =&gt; setSelectedPasskeyId(e.target.value)}<br>      &gt;<br>        &lt;option value=&quot;&quot;&gt;Select a passkey&lt;/option&gt;<br>        {passkeyAccounts.map((account, index) =&gt; (<br>          &lt;option key={account.credentialId} value={account.credentialId}&gt;<br>            Passkey {index + 1}: {account.credentialId.slice(0, 20)}...<br>          &lt;/option&gt;<br>        ))}<br>      &lt;/select&gt;<br>      &lt;button onClick={handleUnlink} disabled={!selectedPasskeyId}&gt;<br>        Unlink Passkey<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>Social Login</strong></p><pre>import { useLinkAccount } from &#39;@privy-io/react-auth&#39;;<br><br>function SocialLogin() {<br>  const { linkEmail, linkGoogle, linkTwitter, linkDiscord } = useLinkAccount();<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={() =&gt; linkEmail()}&gt;Link Email&lt;/button&gt;<br>      &lt;button onClick={() =&gt; linkGoogle()}&gt;Link Google&lt;/button&gt;<br>      &lt;button onClick={() =&gt; linkTwitter()}&gt;Link Twitter&lt;/button&gt;<br>      &lt;button onClick={() =&gt; linkDiscord()}&gt;Link Discord&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3><strong>Wallet Management</strong></h3><p><strong>Creating Wallets</strong></p><pre>import { useCreateWallet } from &#39;@privy-io/react-auth&#39;;<br><br>function CreateWallet() {<br>  const { createWallet } = useCreateWallet({<br>    onSuccess: ({ wallet }) =&gt; {<br>      console.log(&#39;Wallet created:&#39;, wallet.address);<br>      alert(`Wallet created: ${wallet.address}`);<br>    },<br>    onError: (error) =&gt; {<br>      console.error(&#39;Failed to create wallet:&#39;, error);<br>      alert(&#39;Failed to create wallet&#39;);<br>    }<br>  });<br><br>  return (<br>    &lt;button onClick={() =&gt; createWallet()}&gt;<br>      Create New Wallet<br>    &lt;/button&gt;<br>  );<br>}</pre><h3><strong>Accessing Wallets</strong></h3><p><strong>EVM Wallets</strong></p><pre>import { useWallets } from &#39;@privy-io/react-auth&#39;;<br>import { useMemo } from &#39;react&#39;;<br><br>function WalletList() {<br>  const { wallets } = useWallets();<br><br>  const walletInfo = useMemo(() =&gt; {<br>    return wallets.map((wallet) =&gt; ({<br>      address: wallet.address,<br>      chainId: wallet.chainId,<br>      walletClientType: wallet.walletClientType, // &#39;privy&#39;, &#39;metamask&#39;, etc.<br>    }));<br>  }, [wallets]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h3&gt;Your Wallets&lt;/h3&gt;<br>      {walletInfo.map((wallet) =&gt; (<br>        &lt;div key={wallet.address}&gt;<br>          &lt;p&gt;Address: {wallet.address}&lt;/p&gt;<br>          &lt;p&gt;Chain ID: {wallet.chainId}&lt;/p&gt;<br>          &lt;p&gt;Type: {wallet.walletClientType}&lt;/p&gt;<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>Solana Wallets</strong></p><pre>import { useWallets } from &#39;@privy-io/react-auth/solana&#39;;<br><br>function SolanaWalletList() {<br>  const { wallets } = useWallets();<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h3&gt;Solana Wallets&lt;/h3&gt;<br>      {wallets.map((wallet) =&gt; (<br>        &lt;div key={wallet.address}&gt;<br>          &lt;p&gt;Address: {wallet.address}&lt;/p&gt;<br>          &lt;p&gt;Name: {wallet.standardWallet.name}&lt;/p&gt;<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}</pre><h3><strong>Import/Export Wallets</strong></h3><p><strong>Import EVM Wallet</strong></p><pre>import { useImportWallet } from &#39;@privy-io/react-auth&#39;;<br>import { useState } from &#39;react&#39;;<br><br>function ImportEvmWallet() {<br>  const [privateKey, setPrivateKey] = useState(&#39;&#39;);<br>  const { importWallet } = useImportWallet();<br><br>  const handleImport = async () =&gt; {<br>    if (!privateKey.trim()) {<br>      alert(&#39;Please enter a private key&#39;);<br>      return;<br>    }<br><br>    try {<br>      await importWallet({ privateKey });<br>      alert(&#39;Wallet imported successfully!&#39;);<br>      setPrivateKey(&#39;&#39;);<br>    } catch (error) {<br>      console.error(&#39;Import failed:&#39;, error);<br>      alert(&#39;Failed to import wallet&#39;);<br>    }<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input<br>        type=&quot;password&quot;<br>        value={privateKey}<br>        onChange={(e) =&gt; setPrivateKey(e.target.value)}<br>        placeholder=&quot;Enter private key (0x...)&quot;<br>      /&gt;<br>      &lt;button onClick={handleImport}&gt;Import EVM Wallet&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>Import Solana Wallet</strong></p><pre>import { useImportWallet } from &#39;@privy-io/react-auth/solana&#39;;<br>import { useState } from &#39;react&#39;;<br><br>function ImportSolanaWallet() {<br>  const [privateKey, setPrivateKey] = useState(&#39;&#39;);<br>  const { importWallet } = useImportWallet();<br><br>  const handleImport = async () =&gt; {<br>    try {<br>      await importWallet({ privateKey }); // Base58 encoded<br>      alert(&#39;Solana wallet imported successfully!&#39;);<br>      setPrivateKey(&#39;&#39;);<br>    } catch (error) {<br>      console.error(&#39;Import failed:&#39;, error);<br>    }<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input<br>        type=&quot;password&quot;<br>        value={privateKey}<br>        onChange={(e) =&gt; setPrivateKey(e.target.value)}<br>        placeholder=&quot;Enter private key (base58)&quot;<br>      /&gt;<br>      &lt;button onClick={handleImport}&gt;Import Solana Wallet&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>Export Wallet</strong></p><pre>import { usePrivy, useWallets } from &#39;@privy-io/react-auth&#39;;<br><br>function ExportWallet() {<br>  const { exportWallet } = usePrivy();<br>  const { wallets } = useWallets();<br><br>  const handleExport = async () =&gt; {<br>    const privyWallet = wallets.find(w =&gt; w.walletClientType === &#39;privy&#39;);<br>    <br>    if (!privyWallet) {<br>      alert(&#39;No Privy wallet found&#39;);<br>      return;<br>    }<br><br>    try {<br>      // This will show Privy&#39;s export UI<br>      await exportWallet({ address: privyWallet.address });<br>      console.log(&#39;Wallet exported successfully&#39;);<br>    } catch (error) {<br>      console.error(&#39;Export failed:&#39;, error);<br>    }<br>  };<br><br>  return (<br>    &lt;button onClick={handleExport}&gt;<br>      Export Wallet<br>    &lt;/button&gt;<br>  );<br>}</pre><h3><strong>Advanced Features</strong></h3><p><strong>Signing Messages</strong></p><p><strong>EVM Message Signing</strong></p><pre>import { useSignMessage } from &#39;@privy-io/react-auth&#39;;<br><br>function SignEvmMessage() {<br>  const { signMessage } = useSignMessage();<br><br>  const handleSign = async (walletAddress: string) =&gt; {<br>    try {<br>      const message = &#39;Hello, Web3!&#39;;<br>      const uiOptions = {<br>        title: &#39;Sign this message&#39;,<br>        description: &#39;Please sign to verify your wallet ownership&#39;,<br>        buttonText: &#39;Sign Message&#39;<br>      };<br><br>      const { signature } = await signMessage(<br>        { message },<br>        { <br>          uiOptions,<br>          address: walletAddress <br>        }<br>      );<br><br>      console.log(&#39;Signature:&#39;, signature);<br>      alert(`Message signed: ${signature.slice(0, 10)}...`);<br>    } catch (error) {<br>      console.error(&#39;Signing failed:&#39;, error);<br>    }<br>  };<br><br>  return (<br>    &lt;button onClick={() =&gt; handleSign(&#39;0x...&#39;)}&gt;<br>      Sign Message<br>    &lt;/button&gt;<br>  );<br>}</pre><p><strong>Solana Message Signing</strong></p><pre>import { useSignMessage } from &#39;@privy-io/react-auth/solana&#39;;<br>import { useWallets } from &#39;@privy-io/react-auth/solana&#39;;<br>import bs58 from &#39;bs58&#39;;<br><br>function SignSolanaMessage() {<br>  const { signMessage } = useSignMessage();<br>  const { wallets } = useWallets();<br><br>  const handleSign = async () =&gt; {<br>    const wallet = wallets[0];<br>    if (!wallet) return;<br><br>    try {<br>      const message = &#39;Hello, Solana!&#39;;<br>      const signatureUint8Array = await signMessage({<br>        message: new TextEncoder().encode(message),<br>        wallet,<br>        options: {<br>          uiOptions: {<br>            title: &#39;Sign this message&#39;,<br>          },<br>        },<br>      });<br><br>      const signature = bs58.encode(signatureUint8Array.signature);<br>      console.log(&#39;Signature:&#39;, signature);<br>      alert(`Message signed: ${signature.slice(0, 10)}...`);<br>    } catch (error) {<br>      console.error(&#39;Signing failed:&#39;, error);<br>    }<br>  };<br><br>  return (<br>    &lt;button onClick={handleSign}&gt;<br>      Sign Solana Message<br>    &lt;/button&gt;<br>  );<br>}</pre><h3><strong>Sending Transactions</strong></h3><p><strong>EVM Transaction</strong></p><pre>import { useSendTransaction } from &#39;@privy-io/react-auth&#39;;<br><br>function SendEvmTransaction() {<br>  const { sendTransaction } = useSendTransaction();<br><br>  const handleSend = async (walletAddress: string) =&gt; {<br>    try {<br>      const transaction = await sendTransaction(<br>        {<br>          to: &#39;0xRecipientAddress&#39;,<br>          value: 10000, // in wei<br>          // Optional: data, gasLimit, etc.<br>        },<br>        { address: walletAddress }<br>      );<br><br>      console.log(&#39;Transaction:&#39;, transaction);<br>      alert(&#39;Transaction sent successfully!&#39;);<br>    } catch (error) {<br>      console.error(&#39;Transaction failed:&#39;, error);<br>    }<br>  };<br><br>  return (<br>    &lt;button onClick={() =&gt; handleSend(&#39;0x...&#39;)}&gt;<br>      Send Transaction<br>    &lt;/button&gt;<br>  );<br>}</pre><p><strong>Solana Transaction</strong></p><pre>import { useSignAndSendTransaction } from &#39;@privy-io/react-auth/solana&#39;;<br>import { useWallets } from &#39;@privy-io/react-auth/solana&#39;;<br>import {<br>  address,<br>  appendTransactionMessageInstruction,<br>  compileTransaction,<br>  createNoopSigner,<br>  createSolanaRpc,<br>  createTransactionMessage,<br>  getBase64EncodedWireTransaction,<br>  pipe,<br>  setTransactionMessageFeePayer,<br>  setTransactionMessageLifetimeUsingBlockhash,<br>} from &#39;@solana/kit&#39;;<br>import { getTransferSolInstruction } from &#39;@solana-program/system&#39;;<br><br>function SendSolanaTransaction() {<br>  const { signAndSendTransaction } = useSignAndSendTransaction();<br>  const { wallets } = useWallets();<br><br>  const handleSend = async () =&gt; {<br>    const wallet = wallets[0];<br>    if (!wallet) return;<br><br>    try {<br>      const client = createSolanaRpc(&#39;https://api.devnet.solana.com&#39;);<br>      const { value: blockhash } = await client.getLatestBlockhash().send();<br><br>      const transferInstruction = getTransferSolInstruction({<br>        amount: 1000000, // lamports<br>        destination: address(&#39;RecipientPublicKey&#39;),<br>        source: createNoopSigner(address(wallet.address)),<br>      });<br><br>      const transaction = pipe(<br>        createTransactionMessage({ version: 0 }),<br>        (tx) =&gt; setTransactionMessageFeePayer(address(wallet.address), tx),<br>        (tx) =&gt; appendTransactionMessageInstruction(transferInstruction, tx),<br>        (tx) =&gt; setTransactionMessageLifetimeUsingBlockhash(blockhash, tx),<br>        (tx) =&gt; compileTransaction(tx),<br>        (tx) =&gt; getBase64EncodedWireTransaction(tx)<br>      );<br><br>      const receipt = await signAndSendTransaction({<br>        transaction: Buffer.from(transaction, &#39;base64&#39;),<br>        wallet,<br>      });<br><br>      console.log(&#39;Transaction receipt:&#39;, receipt);<br>      alert(&#39;Transaction sent successfully!&#39;);<br>    } catch (error) {<br>      console.error(&#39;Transaction failed:&#39;, error);<br>    }<br>  };<br><br>  return (<br>    &lt;button onClick={handleSend}&gt;<br>      Send Solana Transaction<br>    &lt;/button&gt;<br>  );<br>}</pre><h3><strong>Sign Typed Data (EIP-712)</strong></h3><pre>import { useSignTypedData } from &#39;@privy-io/react-auth&#39;;<br><br>function SignTypedData() {<br>  const { signTypedData } = useSignTypedData();<br><br>  const handleSign = async (walletAddress: string) =&gt; {<br>    try {<br>      const typedData = {<br>        domain: {<br>          name: &#39;My DApp&#39;,<br>          version: &#39;1&#39;,<br>          chainId: 1,<br>          verifyingContract: &#39;0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC&#39;,<br>        },<br>        types: {<br>          Person: [<br>            { name: &#39;name&#39;, type: &#39;string&#39; },<br>            { name: &#39;wallet&#39;, type: &#39;address&#39; },<br>          ],<br>          Mail: [<br>            { name: &#39;from&#39;, type: &#39;Person&#39; },<br>            { name: &#39;to&#39;, type: &#39;Person&#39; },<br>            { name: &#39;contents&#39;, type: &#39;string&#39; },<br>          ],<br>        },<br>        primaryType: &#39;Mail&#39;,<br>        message: {<br>          from: {<br>            name: &#39;Alice&#39;,<br>            wallet: &#39;0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826&#39;,<br>          },<br>          to: {<br>            name: &#39;Bob&#39;,<br>            wallet: &#39;0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB&#39;,<br>          },<br>          contents: &#39;Hello, Bob!&#39;,<br>        },<br>      };<br><br>      const { signature } = await signTypedData(typedData, {<br>        address: walletAddress,<br>      });<br><br>      console.log(&#39;Typed data signature:&#39;, signature);<br>      alert(`Typed data signed: ${signature.slice(0, 10)}...`);<br>    } catch (error) {<br>      console.error(&#39;Signing failed:&#39;, error);<br>    }<br>  };<br><br>  return (<br>    &lt;button onClick={() =&gt; handleSign(&#39;0x...&#39;)}&gt;<br>      Sign Typed Data<br>    &lt;/button&gt;<br>  );<br>}</pre><h3><strong>Sign Raw Hash (Advanced)</strong></h3><pre>import { useWallets } from &#39;@privy-io/react-auth&#39;;<br><br>function SignRawHash() {<br>  const { wallets } = useWallets();<br><br>  const handleSign = async () =&gt; {<br>    const embeddedWallet = wallets.find(<br>      (wallet) =&gt; wallet.walletClientType === &#39;privy&#39;<br>    );<br><br>    if (!embeddedWallet) {<br>      alert(&#39;No embedded wallet found&#39;);<br>      return;<br>    }<br><br>    try {<br>      const provider = await (embeddedWallet as any).getProvider();<br>      const rawHash = &#39;0x6503b027a625549f7be691646404f275f149d17a119a6804b855bac3030037aa&#39;;<br>      <br>      const signature = await provider.request({<br>        method: &#39;secp256k1_sign&#39;,<br>        params: [rawHash],<br>      });<br><br>      console.log(&#39;Raw hash signature:&#39;, signature);<br>      alert(`Raw hash signed: ${signature.slice(0, 10)}...`);<br>    } catch (error) {<br>      console.error(&#39;Signing failed:&#39;, error);<br>    }<br>  };<br><br>  return (<br>    &lt;button onClick={handleSign}&gt;<br>      Sign Raw Hash<br>    &lt;/button&gt;<br>  );<br>}</pre><h3><strong>Best Practices</strong></h3><p><strong>1. Error Handling</strong></p><p>Always wrap Privy operations in try-catch blocks:</p><pre>const handleOperation = async () =&gt; {<br>  try {<br>    await somePrivyOperation();<br>  } catch (error) {<br>    if (error instanceof Error) {<br>      console.error(&#39;Operation failed:&#39;, error.message);<br>      // Show user-friendly error message<br>      alert(`Failed: ${error.message}`);<br>    }<br>  }<br>};</pre><p><strong>2. Loading States</strong></p><p>Manage loading states for better UX:</p><pre>function WalletComponent() {<br>  const [isLoading, setIsLoading] = useState(false);<br>  const { createWallet } = useCreateWallet();<br><br>  const handleCreate = async () =&gt; {<br>    setIsLoading(true);<br>    try {<br>      await createWallet();<br>    } catch (error) {<br>      console.error(error);<br>    } finally {<br>      setIsLoading(false);<br>    }<br>  };<br><br>  return (<br>    &lt;button onClick={handleCreate} disabled={isLoading}&gt;<br>      {isLoading ? &#39;Creating...&#39; : &#39;Create Wallet&#39;}<br>    &lt;/button&gt;<br>  );<br>}</pre><p><strong>3. User Object Management</strong></p><p>Check user state before operations:</p><pre>function SecureComponent() {<br>  const { user, authenticated } = usePrivy();<br><br>  if (!authenticated || !user) {<br>    return &lt;div&gt;Please login first&lt;/div&gt;;<br>  }<br><br>  return &lt;div&gt;Welcome, {user.id}&lt;/div&gt;;<br>}</pre><p><strong>4. Wallet Selection</strong></p><p>Implement proper wallet selection for multi-wallet scenarios:</p><pre>function WalletSelector() {<br>  const { wallets } = useWallets();<br>  const [selectedWallet, setSelectedWallet] = useState&lt;string&gt;(&#39;&#39;);<br><br>  useEffect(() =&gt; {<br>    if (wallets.length &gt; 0 &amp;&amp; !selectedWallet) {<br>      setSelectedWallet(wallets[0].address);<br>    }<br>  }, [wallets, selectedWallet]);<br><br>  return (<br>    &lt;select <br>      value={selectedWallet}<br>      onChange={(e) =&gt; setSelectedWallet(e.target.value)}<br>    &gt;<br>      {wallets.map((wallet) =&gt; (<br>        &lt;option key={wallet.address} value={wallet.address}&gt;<br>          {wallet.address.slice(0, 6)}...{wallet.address.slice(-4)}<br>        &lt;/option&gt;<br>      ))}<br>    &lt;/select&gt;<br>  );<br>}</pre><p><strong>5. Environment Variables</strong></p><p>Never hardcode sensitive data:</p><pre>// ✅ Good<br>const appId = import.meta.env.VITE_PRIVY_APP_ID;<br><br>// ❌ Bad<br>const appId = &#39;clxxx...&#39;;</pre><p><strong>6. Callback Optimization</strong></p><p>Use callbacks for better user feedback:</p><pre>const { createWallet } = useCreateWallet({<br>  onSuccess: ({ wallet }) =&gt; {<br>    // Show success message<br>    toast.success(`Wallet created: ${wallet.address}`);<br>    // Navigate to dashboard<br>    navigate(&#39;/dashboard&#39;);<br>  },<br>  onError: (error) =&gt; {<br>    // Show error message<br>    toast.error(&#39;Failed to create wallet&#39;);<br>    // Log for debugging<br>    console.error(error);<br>  }<br>});</pre><p><strong>7. Type Safety</strong></p><p>Use TypeScript for better type safety:</p><pre>import type { User, ConnectedWallet } from &#39;@privy-io/react-auth&#39;;<br><br>interface WalletComponentProps {<br>  wallet: ConnectedWallet;<br>  user: User;<br>}<br><br>function WalletComponent({ wallet, user }: WalletComponentProps) {<br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;User: {user.id}&lt;/p&gt;<br>      &lt;p&gt;Wallet: {wallet.address}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>8. Memoisation</strong></p><p>Optimise performance with useMemo and useCallback:</p><pre>function OptimizedComponent() {<br>  const { wallets } = useWallets();<br><br>  const walletAddresses = useMemo(() =&gt; {<br>    return wallets.map(w =&gt; w.address);<br>  }, [wallets]);<br><br>  const handleWalletAction = useCallback(async (address: string) =&gt; {<br>    // Perform action<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      {walletAddresses.map(address =&gt; (<br>        &lt;button key={address} onClick={() =&gt; handleWalletAction(address)}&gt;<br>          {address}<br>        &lt;/button&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}</pre><h3><strong>Common Pitfalls</strong></h3><p><strong>1. Not Checking Authentication State</strong></p><pre>// ❌ Bad - May cause errors<br>function BadComponent() {<br>  const { user } = usePrivy();<br>  return &lt;div&gt;{user.id}&lt;/div&gt;; // user might be null<br>}<br><br>// ✅ Good<br>function GoodComponent() {<br>  const { user, authenticated } = usePrivy();<br>  <br>  if (!authenticated || !user) {<br>    return &lt;div&gt;Please login&lt;/div&gt;;<br>  }<br>  <br>  return &lt;div&gt;{user.id}&lt;/div&gt;;<br>}</pre><p><strong>2. Incorrect Hook Usage</strong></p><pre>// ❌ Bad - Hooks must be at top level<br>function BadComponent() {<br>  const handleClick = () =&gt; {<br>    const { login } = usePrivy(); // Wrong!<br>    login();<br>  };<br>}<br><br>// ✅ Good<br>function GoodComponent() {<br>  const { login } = usePrivy();<br>  <br>  const handleClick = () =&gt; {<br>    login();<br>  };<br>}</pre><p><strong>3. Missing Provider</strong></p><pre>// ❌ Bad - Using hooks outside PrivyProvider<br>function App() {<br>  return &lt;MyComponent /&gt;; // Will fail if MyComponent uses Privy hooks<br>}<br><br>// ✅ Good<br>function App() {<br>  return (<br>    &lt;PrivyProvider appId=&quot;...&quot;&gt;<br>      &lt;MyComponent /&gt;<br>    &lt;/PrivyProvider&gt;<br>  );<br>}</pre><p><strong>4. Ignoring Async Operations</strong></p><pre>// ❌ Bad - Not awaiting async operations<br>function BadComponent() {<br>  const { createWallet } = useCreateWallet();<br>  <br>  const handleCreate = () =&gt; {<br>    createWallet(); // Missing await<br>    console.log(&#39;Wallet created&#39;); // Runs before wallet is created<br>  };<br>}<br><br>// ✅ Good<br>function GoodComponent() {<br>  const { createWallet } = useCreateWallet();<br>  <br>  const handleCreate = async () =&gt; {<br>    await createWallet();<br>    console.log(&#39;Wallet created&#39;); // Runs after wallet is created<br>  };<br>}</pre><p><strong>5. Not Handling Multiple Wallets</strong></p><pre>// ❌ Bad - Assuming single wallet<br>function BadComponent() {<br>  const { wallets } = useWallets();<br>  const wallet = wallets[0]; // Might be undefined<br>  return &lt;div&gt;{wallet.address}&lt;/div&gt;;<br>}<br><br>// ✅ Good<br>function GoodComponent() {<br>  const { wallets } = useWallets();<br>  <br>  if (wallets.length === 0) {<br>    return &lt;div&gt;No wallets found&lt;/div&gt;;<br>  }<br>  <br>  return (<br>    &lt;div&gt;<br>      {wallets.map(wallet =&gt; (<br>        &lt;div key={wallet.address}&gt;{wallet.address}&lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>6. Hardcoding Chain IDs</strong></p><pre>// ❌ Bad<br>const chainId = 1; // Hardcoded<br><br>// ✅ Good<br>const SUPPORTED_CHAINS = {<br>  ETHEREUM: 1,<br>  POLYGON: 137,<br>  BASE: 8453,<br>} as const;<br><br>const chainId = SUPPORTED_CHAINS.ETHEREUM;</pre><h3><strong>Security Considerations</strong></h3><p><strong>1. Private Key Handling</strong></p><pre>// ✅ Always use password input type for private keys<br>&lt;input <br>  type=&quot;password&quot; <br>  value={privateKey}<br>  onChange={(e) =&gt; setPrivateKey(e.target.value)}<br>  placeholder=&quot;Enter private key&quot;<br>/&gt;<br><br>// ✅ Clear sensitive data after use<br>const handleImport = async () =&gt; {<br>  try {<br>    await importWallet({ privateKey });<br>    setPrivateKey(&#39;&#39;); // Clear immediately<br>  } catch (error) {<br>    console.error(error);<br>  }<br>};</pre><p><strong>2. Environment Variables</strong></p><pre>// ✅ Use environment variables<br>const config = {<br>  appId: import.meta.env.VITE_PRIVY_APP_ID,<br>  // Never commit .env files to version control<br>};<br><br>// Add to .gitignore<br>// .env<br>// .env.local</pre><p><strong>3. User Verification</strong></p><pre>// ✅ Always verify user before sensitive operations<br>const handleSensitiveOperation = async () =&gt; {<br>  if (!authenticated || !user) {<br>    alert(&#39;Please login first&#39;);<br>    return;<br>  }<br><br>  // Proceed with operation<br>};</pre><p><strong>4. Transaction Validation</strong></p><pre>// ✅ Validate transaction parameters<br>const handleSendTransaction = async (to: string, value: number) =&gt; {<br>  // Validate address<br>  if (!to.match(/^0x[a-fA-F0-9]{40}$/)) {<br>    alert(&#39;Invalid address&#39;);<br>    return;<br>  }<br><br>  // Validate amount<br>  if (value &lt;= 0) {<br>    alert(&#39;Invalid amount&#39;);<br>    return;<br>  }<br><br>  // Proceed with transaction<br>  await sendTransaction({ to, value });<br>};</pre><h3><strong>Performance Optimization</strong></h3><p><strong>1. Code Splitting</strong></p><pre>// Lazy load components<br>import { lazy, Suspense } from &#39;react&#39;;<br><br>const WalletDashboard = lazy(() =&gt; import(&#39;./components/WalletDashboard&#39;));<br><br>function App() {<br>  return (<br>    &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>      &lt;WalletDashboard /&gt;<br>    &lt;/Suspense&gt;<br>  );<br>}</pre><p><strong>2. Memoisation</strong></p><pre>import { useMemo, useCallback } from &#39;react&#39;;<br><br>function OptimizedWalletList() {<br>  const { wallets } = useWallets();<br><br>  // Memoize expensive computations<br>  const sortedWallets = useMemo(() =&gt; {<br>    return [...wallets].sort((a, b) =&gt; <br>      a.address.localeCompare(b.address)<br>    );<br>  }, [wallets]);<br><br>  // Memoize callbacks<br>  const handleWalletClick = useCallback((address: string) =&gt; {<br>    console.log(&#39;Selected wallet:&#39;, address);<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      {sortedWallets.map(wallet =&gt; (<br>        &lt;button <br>          key={wallet.address}<br>          onClick={() =&gt; handleWalletClick(wallet.address)}<br>        &gt;<br>          {wallet.address}<br>        &lt;/button&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>3. Debouncing</strong></p><pre>import { useState, useEffect } from &#39;react&#39;;<br><br>function useDebounce&lt;T&gt;(value: T, delay: number): T {<br>  const [debouncedValue, setDebouncedValue] = useState&lt;T&gt;(value);<br><br>  useEffect(() =&gt; {<br>    const handler = setTimeout(() =&gt; {<br>      setDebouncedValue(value);<br>    }, delay);<br><br>    return () =&gt; {<br>      clearTimeout(handler);<br>    };<br>  }, [value, delay]);<br><br>  return debouncedValue;<br>}<br><br>// Usage<br>function SearchWallets() {<br>  const [searchTerm, setSearchTerm] = useState(&#39;&#39;);<br>  const debouncedSearchTerm = useDebounce(searchTerm, 500);<br><br>  useEffect(() =&gt; {<br>    if (debouncedSearchTerm) {<br>      // Perform search<br>      console.log(&#39;Searching for:&#39;, debouncedSearchTerm);<br>    }<br>  }, [debouncedSearchTerm]);<br><br>  return (<br>    &lt;input<br>      value={searchTerm}<br>      onChange={(e) =&gt; setSearchTerm(e.target.value)}<br>      placeholder=&quot;Search wallets...&quot;<br>    /&gt;<br>  );<br>}</pre><h3><strong>Testing</strong></h3><p><strong>Unit Testing with Jest</strong></p><pre>import { render, screen, waitFor } from &#39;@testing-library/react&#39;;<br>import { PrivyProvider } from &#39;@privy-io/react-auth&#39;;<br>import WalletComponent from &#39;./WalletComponent&#39;;<br><br>// Mock Privy hooks<br>jest.mock(&#39;@privy-io/react-auth&#39;, () =&gt; ({<br>  ...jest.requireActual(&#39;@privy-io/react-auth&#39;),<br>  usePrivy: () =&gt; ({<br>    authenticated: true,<br>    user: { id: &#39;test-user-id&#39; },<br>    login: jest.fn(),<br>    logout: jest.fn(),<br>  }),<br>  useWallets: () =&gt; ({<br>    wallets: [<br>      {<br>        address: &#39;0x1234567890123456789012345678901234567890&#39;,<br>        chainId: &#39;1&#39;,<br>        walletClientType: &#39;privy&#39;,<br>      },<br>    ],<br>  }),<br>}));<br><br>describe(&#39;WalletComponent&#39;, () =&gt; {<br>  it(&#39;renders wallet address&#39;, async () =&gt; {<br>    render(<br>      &lt;PrivyProvider appId=&quot;test-app-id&quot;&gt;<br>        &lt;WalletComponent /&gt;<br>      &lt;/PrivyProvider&gt;<br>    );<br><br>    await waitFor(() =&gt; {<br>      expect(screen.getByText(/0x1234/)).toBeInTheDocument();<br>    });<br>  });<br>});</pre><p><strong>Integration Testing</strong></p><pre>import { render, screen, fireEvent } from &#39;@testing-library/react&#39;;<br>import App from &#39;./App&#39;;<br><br>describe(&#39;App Integration Tests&#39;, () =&gt; {<br>  it(&#39;allows user to login and create wallet&#39;, async () =&gt; {<br>    render(&lt;App /&gt;);<br><br>    // Click login button<br>    const loginButton = screen.getByText(&#39;Login&#39;);<br>    fireEvent.click(loginButton);<br><br>    // Wait for authentication<br>    await waitFor(() =&gt; {<br>      expect(screen.getByText(/Welcome/)).toBeInTheDocument();<br>    });<br><br>    // Click create wallet button<br>    const createWalletButton = screen.getByText(&#39;Create Wallet&#39;);<br>    fireEvent.click(createWalletButton);<br><br>    // Verify wallet was created<br>    await waitFor(() =&gt; {<br>      expect(screen.getByText(/Wallet created/)).toBeInTheDocument();<br>    });<br>  });<br>});</pre><h3><strong>Troubleshooting</strong></h3><p><strong>Common Issues and Solutions</strong></p><p><strong>1. “PrivyProvider not found” Error</strong></p><p><strong>Problem:</strong> Using Privy hooks outside of PrivyProvider</p><h4>Solution:</h4><pre>// ✅ Wrap your app with PrivyProvider<br>function App() {<br>  return (<br>    &lt;PrivyProvider appId=&quot;your-app-id&quot;&gt;<br>      &lt;YourComponent /&gt;<br>    &lt;/PrivyProvider&gt;<br>  );<br>}</pre><p><strong>2. Wallet Not Created After Signup</strong></p><p><strong>Problem:</strong> Wallet creation is not triggered automatically</p><p><strong>Solution:</strong></p><pre>const { signupWithPasskey } = useSignupWithPasskey({<br>  onComplete: async (user) =&gt; {<br>    // Manually trigger wallet creation<br>    await createWallet();<br>  }<br>});</pre><p><strong>3. Transaction Fails Silently</strong></p><p><strong>Problem:</strong> Not handling errors properly</p><p><strong>Solution:</strong></p><pre>try {<br>  await sendTransaction({ to, value });<br>} catch (error) {<br>  console.error(&#39;Transaction error:&#39;, error);<br>  if (error instanceof Error) {<br>    alert(`Transaction failed: ${error.message}`);<br>  }<br>}</pre><p><strong>4. Passkey Not Working on Some Devices</strong></p><p><strong>Problem:</strong> Browser/device doesn’t support WebAuthn</p><p><strong>Solution:</strong></p><pre>// Check for WebAuthn support<br>const isPasskeySupported = () =&gt; {<br>  return window.PublicKeyCredential !== undefined;<br>};<br><br>function AuthComponent() {<br>  const supportsPasskey = isPasskeySupported();<br><br>  return (<br>    &lt;div&gt;<br>      {supportsPasskey ? (<br>        &lt;button onClick={() =&gt; signupWithPasskey()}&gt;<br>          Sign Up with Passkey<br>        &lt;/button&gt;<br>      ) : (<br>        &lt;p&gt;Passkeys not supported on this device&lt;/p&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>5. CORS Errors</strong></p><p><strong>Problem:</strong> CORS issues when making requests</p><p><strong>Solution:</strong></p><p>- Add your domain to the Privy Dashboard allowed origins</p><p>- Ensure you’re using the correct App ID</p><p>- Check that your domain matches exactly (including protocol)</p><h3><strong>Advanced Use Cases</strong></h3><p><strong>1. Multi-Chain Wallet Management</strong></p><pre>import { usePrivy, useWallets } from &#39;@privy-io/react-auth&#39;;<br>import { useState } from &#39;react&#39;;<br><br>function MultiChainWallet() {<br>  const { switchChain } = usePrivy();<br>  const { wallets } = useWallets();<br>  const [selectedChain, setSelectedChain] = useState(1);<br><br>  const chains = [<br>    { id: 1, name: &#39;Ethereum&#39; },<br>    { id: 137, name: &#39;Polygon&#39; },<br>    { id: 8453, name: &#39;Base&#39; },<br>  ];<br><br>  const handleSwitchChain = async (chainId: number) =&gt; {<br>    try {<br>      await switchChain(chainId);<br>      setSelectedChain(chainId);<br>      alert(`Switched to chain ${chainId}`);<br>    } catch (error) {<br>      console.error(&#39;Failed to switch chain:&#39;, error);<br>    }<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h3&gt;Select Network&lt;/h3&gt;<br>      {chains.map((chain) =&gt; (<br>        &lt;button<br>          key={chain.id}<br>          onClick={() =&gt; handleSwitchChain(chain.id)}<br>          disabled={selectedChain === chain.id}<br>        &gt;<br>          {chain.name}<br>        &lt;/button&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>2. Custom Authentication Flow</strong></p><pre>import { usePrivy } from &#39;@privy-io/react-auth&#39;;<br>import { useState } from &#39;react&#39;;<br><br>function CustomAuthFlow() {<br>  const { login, authenticated } = usePrivy();<br>  const [step, setStep] = useState&lt;&#39;welcome&#39; | &#39;auth&#39; | &#39;complete&#39;&gt;(&#39;welcome&#39;);<br><br>  const handleStartAuth = () =&gt; {<br>    setStep(&#39;auth&#39;);<br>    login();<br>  };<br><br>  if (authenticated) {<br>    return &lt;div&gt;Welcome! You&#39;re authenticated.&lt;/div&gt;;<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      {step === &#39;welcome&#39; &amp;&amp; (<br>        &lt;div&gt;<br>          &lt;h1&gt;Welcome to Our DApp&lt;/h1&gt;<br>          &lt;p&gt;Get started by connecting your wallet&lt;/p&gt;<br>          &lt;button onClick={handleStartAuth}&gt;Get Started&lt;/button&gt;<br>        &lt;/div&gt;<br>      )}<br>      {step === &#39;auth&#39; &amp;&amp; (<br>        &lt;div&gt;<br>          &lt;p&gt;Authenticating...&lt;/p&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>3. Wallet Balance Display</strong></p><pre>import { useWallets } from &#39;@privy-io/react-auth&#39;;<br>import { useState, useEffect } from &#39;react&#39;;<br>import { ethers } from &#39;ethers&#39;;<br><br>function WalletBalance() {<br>  const { wallets } = useWallets();<br>  const [balances, setBalances] = useState&lt;Record&lt;string, string&gt;&gt;({});<br><br>  useEffect(() =&gt; {<br>    const fetchBalances = async () =&gt; {<br>      const provider = new ethers.JsonRpcProvider(&#39;https://eth.llamarpc.com&#39;);<br>      <br>      const balancePromises = wallets.map(async (wallet) =&gt; {<br>        const balance = await provider.getBalance(wallet.address);<br>        return {<br>          address: wallet.address,<br>          balance: ethers.formatEther(balance),<br>        };<br>      });<br><br>      const results = await Promise.all(balancePromises);<br>      const balanceMap = results.reduce((acc, { address, balance }) =&gt; {<br>        acc[address] = balance;<br>        return acc;<br>      }, {} as Record&lt;string, string&gt;);<br><br>      setBalances(balanceMap);<br>    };<br><br>    if (wallets.length &gt; 0) {<br>      fetchBalances();<br>    }<br>  }, [wallets]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h3&gt;Wallet Balances&lt;/h3&gt;<br>      {wallets.map((wallet) =&gt; (<br>        &lt;div key={wallet.address}&gt;<br>          &lt;p&gt;{wallet.address}&lt;/p&gt;<br>          &lt;p&gt;Balance: {balances[wallet.address] || &#39;Loading...&#39;} ETH&lt;/p&gt;<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>4. Session Management</strong></p><pre>import { usePrivy } from &#39;@privy-io/react-auth&#39;;<br>import { useEffect } from &#39;react&#39;;<br><br>function SessionManager() {<br>  const { authenticated, user, logout } = usePrivy();<br><br>  useEffect(() =&gt; {<br>    if (!authenticated) return;<br><br>    // Set session timeout (30 minutes)<br>    const SESSION_TIMEOUT = 30 * 60 * 1000;<br>    let timeoutId: NodeJS.Timeout;<br><br>    const resetTimeout = () =&gt; {<br>      clearTimeout(timeoutId);<br>      timeoutId = setTimeout(() =&gt; {<br>        alert(&#39;Session expired. Please login again.&#39;);<br>        logout();<br>      }, SESSION_TIMEOUT);<br>    };<br><br>    // Reset timeout on user activity<br>    const events = [&#39;mousedown&#39;, &#39;keydown&#39;, &#39;scroll&#39;, &#39;touchstart&#39;];<br>    events.forEach((event) =&gt; {<br>      document.addEventListener(event, resetTimeout);<br>    });<br><br>    resetTimeout();<br><br>    return () =&gt; {<br>      clearTimeout(timeoutId);<br>      events.forEach((event) =&gt; {<br>        document.removeEventListener(event, resetTimeout);<br>      });<br>    };<br>  }, [authenticated, logout]);<br><br>  return null; // This is a utility component<br>}</pre><p><strong>5. Transaction History</strong></p><pre>import { useWallets } from &#39;@privy-io/react-auth&#39;;<br>import { useState, useEffect } from &#39;react&#39;;<br><br>interface Transaction {<br>  hash: string;<br>  from: string;<br>  to: string;<br>  value: string;<br>  timestamp: number;<br>}<br><br>function TransactionHistory() {<br>  const { wallets } = useWallets();<br>  const [transactions, setTransactions] = useState&lt;Transaction[]&gt;([]);<br>  const [loading, setLoading] = useState(false);<br><br>  useEffect(() =&gt; {<br>    const fetchTransactions = async () =&gt; {<br>      if (wallets.length === 0) return;<br><br>      setLoading(true);<br>      try {<br>        const wallet = wallets[0];<br>        // Use Etherscan API or similar<br>        const response = await fetch(<br>          `https://api.etherscan.io/api?module=account&amp;action=txlist&amp;address=${wallet.address}&amp;sort=desc`<br>        );<br>        const data = await response.json();<br>        <br>        if (data.status === &#39;1&#39;) {<br>          const txs = data.result.slice(0, 10).map((tx: any) =&gt; ({<br>            hash: tx.hash,<br>            from: tx.from,<br>            to: tx.to,<br>            value: (parseInt(tx.value) / 1e18).toFixed(4),<br>            timestamp: parseInt(tx.timeStamp),<br>          }));<br>          setTransactions(txs);<br>        }<br>      } catch (error) {<br>        console.error(&#39;Failed to fetch transactions:&#39;, error);<br>      } finally {<br>        setLoading(false);<br>      }<br>    };<br><br>    fetchTransactions();<br>  }, [wallets]);<br><br>  if (loading) return &lt;div&gt;Loading transactions...&lt;/div&gt;;<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h3&gt;Recent Transactions&lt;/h3&gt;<br>      {transactions.length === 0 ? (<br>        &lt;p&gt;No transactions found&lt;/p&gt;<br>      ) : (<br>        &lt;ul&gt;<br>          {transactions.map((tx) =&gt; (<br>            &lt;li key={tx.hash}&gt;<br>              &lt;p&gt;Hash: {tx.hash.slice(0, 10)}...&lt;/p&gt;<br>              &lt;p&gt;Value: {tx.value} ETH&lt;/p&gt;<br>              &lt;p&gt;Date: {new Date(tx.timestamp * 1000).toLocaleDateString()}&lt;/p&gt;<br>            &lt;/li&gt;<br>          ))}<br>        &lt;/ul&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}</pre><h3><strong>Resources</strong></h3><p><strong>Official Documentation</strong></p><p>- [<a href="https://docs.privy.io/">Privy Documentation</a>](https://docs.privy.io/)</p><p>- [<a href="https://dashboard.privy.io/">Privy Dashboard</a>](https://dashboard.privy.io/)</p><p>- [<a href="https://github.com/amitpatel-wstf/Privy-WebView">GitHub</a>]</p><p><strong>Related Technologies</strong></p><p>- [<a href="https://webauthn.guide/">WebAuthn Guide</a>](https://webauthn.guide/)</p><p>- [<a href="https://ethereum.org/en/developers/docs/">Ethereum Documentation</a>](https://ethereum.org/en/developers/docs/)</p><p>- [<a href="https://docs.solana.com/">Solana Documentation</a>](https://docs.solana.com/)</p><p><strong>Tools</strong></p><p>- [<a href="https://etherscan.io/">Etherscan</a>](https://etherscan.io/) — Ethereum blockchain explorer</p><p>- [<a href="https://solscan.io/">Solscan</a>](https://solscan.io/) — Solana blockchain explorer</p><p>- [<a href="https://metamask.io/">MetaMask</a>](https://metamask.io/) — Browser wallet</p><p>- [<a href="https://phantom.app/">Phantom</a>](https://phantom.app/) — Solana wallet</p><h3><strong>Conclusion</strong></h3><p>Privy provides a powerful, developer-friendly solution for integrating Web3 authentication and wallet management into your applications. By following this guide, you should be able to:</p><p>✅ Set up Privy in React and React Native applications</p><p>✅ Implement multiple authentication methods including passkeys</p><p>✅ Manage EVM and Solana wallets</p><p>✅ Sign messages and send transactions</p><p>✅ Handle advanced use cases like multi-chain support</p><p>✅ Follow best practices for security and performance</p><p><strong>Key Takeaways</strong></p><p>1. <strong>Start Simple</strong>: Begin with basic authentication and gradually add features</p><p>2. <strong>Error Handling</strong>: Always implement proper error handling and user feedback</p><p>3. <strong>Security First</strong>: Never expose private keys or sensitive data</p><p>4. <strong>User Experience</strong>: Provide clear loading states and helpful error messages</p><p>5. <strong>Testing</strong>: Test across different browsers and devices</p><p>6. <strong>Documentation</strong>: Keep your implementation well-documented</p><h3><strong>Next Steps</strong></h3><p>1. Explore the [<a href="https://dashboard.privy.io/">Privy Dashboard</a>](https://dashboard.privy.io/) for advanced configuration</p><p>2. Join the [<a href="https://discord.gg/privy">Privy Discord</a>](https://discord.gg/privy) community for support</p><p>3. Check out example projects on [<a href="https://github.com/amitpatel-wstf/Privy-WebView">GitHub</a>](<a href="https://github.com/amitpatel-wstf/Privy-WebView">https://github.com/amitpatel-wstf/Privy-WebView</a>)</p><p>4. Experiment with different authentication flows</p><p>5. Implement custom UI components for better branding</p><h3><strong>Appendix: Quick Reference</strong></h3><p><strong>Essential Hooks</strong></p><pre>// Authentication<br>const { login, logout, authenticated, user } = usePrivy();<br><br>// Wallets<br>const { wallets } = useWallets();<br>const { createWallet } = useCreateWallet();<br><br>// Signing<br>const { signMessage } = useSignMessage();<br>const { signTypedData } = useSignTypedData();<br><br>// Transactions<br>const { sendTransaction } = useSendTransaction();<br><br>// Passkeys<br>const { loginWithPasskey } = useLoginWithPasskey();<br>const { signupWithPasskey } = useSignupWithPasskey();<br>const { linkWithPasskey } = useLinkWithPasskey();</pre><p><strong>Common Patterns</strong></p><pre>// Check authentication<br>if (!authenticated || !user) {<br>  return &lt;LoginScreen /&gt;;<br>}<br><br>// Handle async operations<br>const handleOperation = async () =&gt; {<br>  try {<br>    await operation();<br>  } catch (error) {<br>    console.error(error);<br>  }<br>};<br><br>// Memoize expensive computations<br>const data = useMemo(() =&gt; computeData(), [dependencies]);<br><br>// Callback optimization<br>const callback = useCallback(() =&gt; {<br>  // Do something<br>}, [dependencies]);</pre><p><strong>Author</strong>: Amit Patel</p><p><strong>Last Updated: Nov 2025</strong></p><p><strong>Version:</strong> 1.0.0</p><p>For questions or feedback, please open an issue on <a href="https://github.com/amitpatel-wstf">GitHub</a> , <a href="https://t.me/TheDev77">Telegram</a>, <a href="https://x.com/AmitPatel_Dev">Twitter</a> or reach out on Discord.</p><p>Happy buildin</p><p>10. [Common Pitfalls](#common-pitfalls)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c9d6de0dd10" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>