From 14f7b4ef47a45fea0f6731095ce2283e68e2aa52 Mon Sep 17 00:00:00 2001 From: youssefea Date: Fri, 8 Aug 2025 17:50:55 +0100 Subject: [PATCH 1/3] update wagmi section --- .../framework-integrations/wagmi/base-pay.mdx | 60 +++++ .../wagmi/other-use-cases.mdx | 106 +++++++++ .../wagmi/sign-in-with-base.mdx | 222 +++--------------- docs/docs.json | 4 +- 4 files changed, 205 insertions(+), 187 deletions(-) create mode 100644 docs/base-account/framework-integrations/wagmi/base-pay.mdx create mode 100644 docs/base-account/framework-integrations/wagmi/other-use-cases.mdx diff --git a/docs/base-account/framework-integrations/wagmi/base-pay.mdx b/docs/base-account/framework-integrations/wagmi/base-pay.mdx new file mode 100644 index 000000000..55b02114c --- /dev/null +++ b/docs/base-account/framework-integrations/wagmi/base-pay.mdx @@ -0,0 +1,60 @@ +--- +title: "Base Pay" +description: "Accept USDC payments with Base Pay in your Wagmi-powered React application" +--- + +Base Pay works the same way in Wagmi applications as it does anywhere else - it operates independently of wallet connections and uses the Base Account SDK directly. + +## Implementation + +Base Pay doesn't require any special Wagmi integration. Simply follow the [Accept Payments guide](/base-account/guides/accept-payments) - all the code examples work exactly the same in your Wagmi app. + +The key points: + +- **No wallet connection needed** - Base Pay handles everything through the SDK +- **Same API** - Use `pay()` and `getPaymentStatus()` exactly as shown in the main guide +- **Works alongside Wagmi** - You can display the user's connected address from `useAccount()` but it's not required for payments + +## Quick Example + +```tsx +import { pay } from '@base-org/account' +import { useAccount } from 'wagmi' // Optional - just for display + +export function CheckoutButton() { + const { address } = useAccount() // Optional + + const handlePayment = async () => { + try { + const payment = await pay({ + amount: '5.00', + to: '0xYourAddress', + testnet: true + }) + console.log('Payment sent:', payment.id) + } catch (error) { + console.error('Payment failed:', error) + } + } + + return ( +
+ {address &&

Connected: {address}

} + +
+ ) +} +``` + + +**Please Follow the Brand Guidelines** + +If you intend on using the `BasePayButton`, please follow the [Brand Guidelines](/base-account/reference/ui-elements/brand-guidelines) to ensure consistency across your application. + + + +## Learn More + +For complete implementation details, examples, and advanced features like collecting user information, see the main [Accept Payments guide](/base-account/guides/accept-payments). diff --git a/docs/base-account/framework-integrations/wagmi/other-use-cases.mdx b/docs/base-account/framework-integrations/wagmi/other-use-cases.mdx new file mode 100644 index 000000000..b55690639 --- /dev/null +++ b/docs/base-account/framework-integrations/wagmi/other-use-cases.mdx @@ -0,0 +1,106 @@ +--- +title: "Other Use Cases" +description: "Access the Base Account provider from Wagmi for advanced functionality like Sub Accounts, Spend Permissions, and more" +--- + +Learn how to access the Base Account provider through Wagmi to unlock advanced Base Account features beyond basic authentication and payments. + +## Prerequisites + +Make sure you have [set up Wagmi with Base Account](/base-account/framework-integrations/wagmi/setup) before following this guide. + +## Getting the Provider + +The key to accessing advanced Base Account functionality is getting the provider from your Wagmi connector. Once you have the provider, you can use any Base Account RPC method. + + +```tsx Hook +// hooks/useBaseAccountProvider.ts +import { useConnector, useAccount } from 'wagmi' +import { useEffect, useState } from 'react' + +export function useBaseAccountProvider() { + const { isConnected } = useAccount() + const connector = useConnector() + const [provider, setProvider] = useState(null) + + useEffect(() => { + if (isConnected && connector) { + // Access the Base Account provider + const baseAccountProvider = connector.provider + setProvider(baseAccountProvider) + } else { + setProvider(null) + } + }, [isConnected, connector]) + + return provider +} +``` +```tsx Component +// components/BaseAccountFeatures.tsx +import { useBaseAccountProvider } from '../hooks/useBaseAccountProvider' +import { useAccount } from 'wagmi' + +export function BaseAccountFeatures() { + const { address, isConnected } = useAccount() + const provider = useBaseAccountProvider() + + const callProviderMethod = async (method: string, params: any[]) => { + if (!provider) { + console.error('Provider not available') + return + } + + try { + const result = await provider.request({ + method, + params + }) + console.log(`${method} result:`, result) + return result + } catch (error) { + console.error(`${method} error:`, error) + throw error + } + } + + if (!isConnected) { + return

Please connect your wallet to access Base Account features

+ } + + return ( +
+

Base Account Features

+

+ Connected with Base Account provider. You can now access advanced features. +

+
+ ) +} +``` +
+ +## Available Use Cases + +Once you have the provider, you can access all Base Account functionality: + +### Sub Accounts +Create and manage child accounts for improved UX. + +**Learn more:** [Sub Accounts Guide](/base-account/improve-ux/sub-accounts) | [Sub Accounts RPC Method](/base-account/reference/core/provider-rpc-methods/wallet_addSubAccount) + +### Spend Permissions +Allow apps to spend on behalf of users with predefined limits. + +**Learn more:** [Spend Permissions Guide](/base-account/improve-ux/spend-permissions) | [Spend Permissions Reference](/base-account/reference/spend-permission-utilities/requestSpendPermission) + +### Batch Transactions +Execute multiple transactions in a single user confirmation. + +**Learn more:** [Batch Transactions Guide](/base-account/improve-ux/batch-transactions) | [`wallet_sendCalls` Reference](/base-account/reference/core/provider-rpc-methods/wallet_sendCalls) + +### Gasless Transactions +Sponsor gas fees for your users. + +**Learn more:** [Gasless Transactions Guide](/base-account/improve-ux/paymaster) | [Coinbase Developer Platform Paymaster](https://docs.cdp.coinbase.com/paymaster/introduction/welcome) diff --git a/docs/base-account/framework-integrations/wagmi/sign-in-with-base.mdx b/docs/base-account/framework-integrations/wagmi/sign-in-with-base.mdx index 45223c1f5..49afe706f 100644 --- a/docs/base-account/framework-integrations/wagmi/sign-in-with-base.mdx +++ b/docs/base-account/framework-integrations/wagmi/sign-in-with-base.mdx @@ -22,12 +22,10 @@ This follows the same flow as shown in the [authenticate users guide](/base-acco ## Implementation -### 1. Basic Sign In Component +### Code Snippets -Create a component that handles the complete authentication flow: - -```tsx -// components/SignInWithBase.tsx + +```ts Browser (Wagmi + SDK) import { useState } from 'react' import { useConnect, useAccount, useDisconnect } from 'wagmi' import { baseAccount } from 'wagmi/connectors' @@ -54,16 +52,16 @@ export function SignInWithBase() { setError(null) try { - // 1. Generate or fetch nonce + // 1 — get a fresh nonce (generate locally or prefetch from backend) const nonce = window.crypto.randomUUID().replace(/-/g, '') - // OR fetch from your backend: + // OR prefetch from server // const nonce = await fetch('/auth/nonce').then(r => r.text()) - // 2. Connect and get the provider - const result = await connectAsync({ connector: baseAccountConnector }) - const provider = await baseAccountConnector.getProvider() + // 2 — connect and get the provider + await connectAsync({ connector: baseAccountConnector }) + const provider = baseAccountConnector.provider - // 3. Use wallet_connect with signInWithEthereum capabilities + // 3 — authenticate with wallet_connect const authResult = await provider.request({ method: 'wallet_connect', params: [{ @@ -81,132 +79,55 @@ export function SignInWithBase() { const { address, capabilities } = accounts[0] const { message, signature } = capabilities.signInWithEthereum - // 4. Verify signature on your backend - const response = await fetch('/auth/verify', { + // 4 — verify on backend + await fetch('/auth/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ address, message, signature }) }) - - if (!response.ok) { - throw new Error('Authentication failed') - } - - const authData = await response.json() - console.log('Authentication successful:', authData) - - // Handle successful authentication (e.g., redirect, update state) - } catch (err: any) { - console.error('Sign in failed:', err) + console.error(`err ${err}`) setError(err.message || 'Sign in failed') } finally { setIsLoading(false) } } - const handleSignOut = () => { - disconnect() - // Clear any auth state in your app - } - if (isConnected) { return (
-
- Connected as: - {address} -
- + {address} +
) } return ( -
- - - {error && ( -
- {error} -
- )} -
+ ) } ``` - -### 2. Backend Verification - -Set up your backend to verify the signatures (following the authenticate users guide): - -```ts -// pages/api/auth/nonce.ts (optional - you can generate client-side) -export default function handler(req: any, res: any) { - const nonce = crypto.randomBytes(16).toString('hex') - // Store nonce in session/database to prevent reuse - res.json({ nonce }) -} -``` - -```ts -// pages/api/auth/verify.ts -import { createPublicClient, http } from 'viem' -import { base } from 'viem/chains' - -const client = createPublicClient({ - chain: base, - transport: http() -}) - -export default async function handler(req: any, res: any) { - if (req.method !== 'POST') { - return res.status(405).json({ error: 'Method not allowed' }) - } - - const { address, message, signature } = req.body - - try { - // 1. Verify the signature (automatically handles ERC-6492 for undeployed wallets) - const isValid = await client.verifyMessage({ - address, - message, - signature - }) - - if (!isValid) { - return res.status(401).json({ error: 'Invalid signature' }) - } - - // 2. Create session/JWT here - // const token = jwt.sign({ address }, process.env.JWT_SECRET) - - res.json({ - success: true, - address, - // token - }) - } catch (error) { - console.error('Verification error:', error) - res.status(500).json({ error: 'Verification failed' }) - } +```ts Backend (Viem) +import { createPublicClient, http } from 'viem'; +import { base } from 'viem/chains'; + +const client = createPublicClient({ chain: base, transport: http() }); + +export async function verifySig(req, res) { + const { address, message, signature } = req.body; + const valid = await client.verifyMessage({ address, message, signature }); + if (!valid) return res.status(401).json({ error: 'Invalid signature' }); + // create session / JWT + res.json({ ok: true }); } ``` +
### 3. Using the Pre-built Button Component -You can also use the official Base Account UI button component: +You can also use the official [Sign In With Base](/base-account/reference/ui-elements/sign-in-with-base-button) button component: ```tsx // components/SignInButton.tsx @@ -229,7 +150,7 @@ export function SignInButton() { // Connect and get provider await connectAsync({ connector: baseAccountConnector }) - const provider = await baseAccountConnector.getProvider() + const provider = baseAccountConnector.provider // Perform SIWE authentication const authResult = await provider.request({ @@ -270,80 +191,9 @@ export function SignInButton() { } ``` -### 4. Complete App Example - -Here's a complete example integrating everything: - -```tsx -// app/page.tsx -'use client' -import { SignInWithBase } from '../components/SignInWithBase' -import { useAccount } from 'wagmi' - -export default function HomePage() { - const { isConnected, address } = useAccount() - - return ( -
-
-

My App

- - {!isConnected ? ( - <> -

- Sign in with your Base Account to continue -

- - - ) : ( -
-
-

Welcome!

-

- You're signed in with Base Account -

-
- - -
- )} -
-
- ) -} -``` - -## Error Handling - -Handle common error scenarios: - -```tsx -const handleSignIn = async () => { - try { - // ... authentication logic - } catch (err: any) { - if (err.code === 4001) { - setError('User rejected the sign in request') - } else if (err.code === -32002) { - setError('Sign in request already pending') - } else if (err.message?.includes('method_not_supported')) { - // Fallback for wallets that don't support wallet_connect - setError('Please update your wallet to use Sign in with Base') - } else { - setError('Sign in failed. Please try again.') - } - } -} -``` - -## Notes - -- The `wallet_connect` method with `signInWithEthereum` capabilities is the recommended approach for Base Account authentication -- For wallets that don't support `wallet_connect`, you may need to implement a fallback using `eth_requestAccounts` and `personal_sign` -- Always verify signatures on your backend using a ERC-6492 compatible library like Viem -- Generate nonces securely and ensure they can't be reused + +**Please Follow the Brand Guidelines** -## Next Steps +If you intend on using the `SignInWithBaseButton`, please follow the [Brand Guidelines](/base-account/reference/ui-elements/brand-guidelines) to ensure consistency across your application. -- [Learn about Sub Accounts with Wagmi](/base-account/framework-integrations/wagmi/sub-accounts) -- [Explore the authenticate users guide](/base-account/guides/authenticate-users) + \ No newline at end of file diff --git a/docs/docs.json b/docs/docs.json index 1c84547e8..46fc0969a 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -206,7 +206,9 @@ "group": "Wagmi", "pages": [ "base-account/framework-integrations/wagmi/setup", - "base-account/framework-integrations/wagmi/sub-accounts" + "base-account/framework-integrations/wagmi/sign-in-with-base", + "base-account/framework-integrations/wagmi/base-pay", + "base-account/framework-integrations/wagmi/other-use-cases" ] }, { From 5dfcdfee3eae04caa21175df82abed786480b1fa Mon Sep 17 00:00:00 2001 From: youssefea Date: Mon, 11 Aug 2025 14:03:27 +0100 Subject: [PATCH 2/3] update setup docs --- .../framework-integrations/wagmi/setup.mdx | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/docs/base-account/framework-integrations/wagmi/setup.mdx b/docs/base-account/framework-integrations/wagmi/setup.mdx index b2f25d991..028767486 100644 --- a/docs/base-account/framework-integrations/wagmi/setup.mdx +++ b/docs/base-account/framework-integrations/wagmi/setup.mdx @@ -9,17 +9,11 @@ Learn how to set up Wagmi with Base Account to enable Base Account SDK functiona [Wagmi](https://wagmi.sh/) is a collection of React hooks for Ethereum Virtual Machine (EVM) compatible networks that makes it easy to work with wallets, contracts, transactions, and signing. Base Account integrates perfectly with Wagmi, allowing you to use all your familiar hooks. -### What you'll achieve - -By the end of this guide, you will: - -- Set up Wagmi with Base Account connector -- Configure your React application for Base Account -- Use standard Wagmi hooks with Base Account - ## Installation -After [creating a new Next.js project](https://nextjs.org/docs/app/getting-started/installation), install the required dependencies: +If you start [a new wagmi project](https://wagmi.sh/react/getting-started), you can skip the installation step. + +If you already have a project, you can install the dependencies with your package manager of choice: ```bash npm @@ -40,7 +34,7 @@ bun add wagmi viem @base-org/account -You can also use the command line `npm create wagmi@latest` to create a new full Wagmi project. +To create a new wagmi project, you can use the command line `npm create wagmi@latest`. ## Configuration @@ -97,4 +91,4 @@ export default function App({ children }: { children: React.ReactNode }) { Now that you have Wagmi configured with Base Account, you can: - [Connect users with Sign in with Base](/base-account/framework-integrations/wagmi/sign-in-with-base) -- [Implement Sub Accounts functionality](/base-account/framework-integrations/wagmi/sub-accounts) +- [Access the Base Account provider](/base-account/framework-integrations/wagmi/other-use-cases) \ No newline at end of file From 701f42eac061a7aa3ade88b3d7bc435c914bbee4 Mon Sep 17 00:00:00 2001 From: youssefea Date: Mon, 11 Aug 2025 15:41:19 +0100 Subject: [PATCH 3/3] update link --- .../framework-integrations/wagmi/other-use-cases.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/base-account/framework-integrations/wagmi/other-use-cases.mdx b/docs/base-account/framework-integrations/wagmi/other-use-cases.mdx index b55690639..8b846103f 100644 --- a/docs/base-account/framework-integrations/wagmi/other-use-cases.mdx +++ b/docs/base-account/framework-integrations/wagmi/other-use-cases.mdx @@ -103,4 +103,4 @@ Execute multiple transactions in a single user confirmation. ### Gasless Transactions Sponsor gas fees for your users. -**Learn more:** [Gasless Transactions Guide](/base-account/improve-ux/paymaster) | [Coinbase Developer Platform Paymaster](https://docs.cdp.coinbase.com/paymaster/introduction/welcome) +**Learn more:** [Gasless Transactions Guide](/base-account/improve-ux/sponsor-gas/paymaster) | [Coinbase Developer Platform Paymaster](https://docs.cdp.coinbase.com/paymaster/introduction/welcome)