-
-
Notifications
You must be signed in to change notification settings - Fork 2k
[Smart Accounts Kit ] add delegations buyer guide for x402 #2912
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 6 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
b586968
add delegations buyer guide
AyushBherwani1998 e7ae56e
update step title
AyushBherwani1998 ef8566c
add advanced permission buyer guide
AyushBherwani1998 5ad13ab
add recurring payments guide
AyushBherwani1998 370a69c
fix typo
AyushBherwani1998 460383c
Merge branch 'main' into feat/buyer
AyushBherwani1998 50af603
clean up code snippets
AyushBherwani1998 7c00f7f
Merge branch 'main' into feat/buyer
AyushBherwani1998 d981a1f
Apply suggestions from code review
AyushBherwani1998 37df431
Merge branch 'main' into feat/buyer
AyushBherwani1998 9559bae
minor fixes
AyushBherwani1998 fdbf318
add link to rule reference
AyushBherwani1998 9915b95
resolve review comments
AyushBherwani1998 5646278
Merge branch 'main' into feat/buyer
AyushBherwani1998 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
289 changes: 289 additions & 0 deletions
289
smart-accounts-kit/guides/x402/buyer/advanced-permissions.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,289 @@ | ||
| --- | ||
| description: Access an x402-protected API data using Advanced Permissions with a fixed allowance. | ||
| sidebar_label: Advanced Permissions | ||
| keywords: | ||
| [x402, ERC-7715, ERC-7710, advanced permissions, redeemers, allowance, session account, buyer] | ||
| --- | ||
|
|
||
| import Tabs from '@theme/Tabs'; | ||
| import TabItem from '@theme/TabItem'; | ||
| import GlossaryTerm from '@theme/GlossaryTerm'; | ||
|
|
||
| # Pay for an x402 API with Advanced Permissions | ||
|
|
||
| In this guide, you request <GlossaryTerm term="Advanced Permissions" /> with a fixed ERC-20 allowance | ||
| to pay for a specific x402-protected resource. | ||
|
|
||
| ## Prerequisites | ||
|
|
||
| - [Install and set up the Smart Accounts Kit.](../../../get-started/install.md) | ||
|
|
||
| ## Steps | ||
|
|
||
| ### 1. Set up a Wallet Client | ||
|
|
||
| Set up a Wallet Client using Viem's [`createWalletClient`](https://viem.sh/docs/clients/wallet) function. This client will | ||
| help you interact with MetaMask. | ||
|
AyushBherwani1998 marked this conversation as resolved.
Outdated
|
||
|
|
||
| Then, extend the Wallet Client functionality using `erc7715ProviderActions`. | ||
| These actions enable you to request <GlossaryTerm term="Advanced Permissions" /> from the user. | ||
|
AyushBherwani1998 marked this conversation as resolved.
Outdated
|
||
|
|
||
| ```typescript | ||
| import { createWalletClient, custom } from 'viem' | ||
| import { erc7715ProviderActions } from '@metamask/smart-accounts-kit/actions' | ||
|
|
||
| const walletClient = createWalletClient({ | ||
| transport: custom(window.ethereum), | ||
| }).extend(erc7715ProviderActions()) | ||
| ``` | ||
|
|
||
| ### 2. Set up a session account | ||
|
|
||
| Set up a session account. The requested permissions are granted to the session account, which is responsible for making x402 API calls. | ||
|
bgravenorst marked this conversation as resolved.
|
||
|
|
||
| The session account can be either a smart account or an EOA. This examples uses EOA as a session account. | ||
|
AyushBherwani1998 marked this conversation as resolved.
Outdated
|
||
|
|
||
| ```typescript | ||
| import { privateKeyToAccount } from 'viem/accounts' | ||
| import { sepolia as chain } from 'viem/chains' | ||
| import { createWalletClient, http } from 'viem' | ||
|
|
||
| const sessionAccount = privateKeyToAccount('0x...') | ||
| ``` | ||
|
|
||
| ### 3. Get payment requirements | ||
|
|
||
| Call the protected API route once without a payment header. | ||
|
|
||
| The server returns `402` with the payment terms (`PAYMENT-REQUIRED`) in the response, which you use | ||
| to build the payment payload. | ||
|
|
||
| <Tabs> | ||
| <TabItem value="example.ts"> | ||
|
|
||
| ```ts | ||
| import { PaymentRequirements } from './types' | ||
|
|
||
| // Update the URL | ||
| const challengeResponse = await fetch('https://api.example.com/paid-endpoint') | ||
| if (challengeResponse.status !== 402) { | ||
| console.error('Expected 402 challenge from protected route') | ||
| // Handle error | ||
| } | ||
|
|
||
| const paymentRequiredHeader = challengeResponse.headers.get('PAYMENT-REQUIRED') | ||
| if (!paymentRequiredHeader) { | ||
| console.error('PAYMENT-REQUIRED header is missing') | ||
| // Handle error | ||
| } | ||
|
|
||
| const decodedPaymentRequired = Buffer.from(paymentRequiredHeader, 'base64').toString('utf-8') | ||
| const paymentRequired = JSON.parse(decodedPaymentRequired) as { | ||
| accepts: PaymentRequirements[] | ||
| } | ||
|
|
||
| const accepted = paymentRequired.accepts[0] | ||
| if (!accepted) { | ||
| console.error('Server did not provide accepted payment requirements') | ||
| // Handle error | ||
| } | ||
|
|
||
| if (accepted.extra.assetTransferMethod !== 'erc7710') { | ||
| console.error('Server does not support ERC-7710 delegation payments') | ||
| // Handle error | ||
| } | ||
| ``` | ||
|
|
||
| </TabItem> | ||
| <TabItem value="types.ts"> | ||
|
|
||
| ```ts | ||
| import { Address } from 'viem' | ||
|
|
||
| export type PaymentRequirements = { | ||
| scheme: string | ||
| network: string | ||
| amount: string | ||
| asset: Address | ||
| payTo: Address | ||
| maxTimeoutSeconds: number | ||
| extra: { | ||
| assetTransferMethod: string | ||
| facilitators?: Address[] | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| </TabItem> | ||
| </Tabs> | ||
|
|
||
| ### 4. Request Advanced Permissions | ||
|
|
||
| Request Advanced Permissions from the user with the Wallet Client's `requestExecutionPermissions` action. | ||
|
|
||
| In this example, you request an ERC-20 allowance permission with a fixed allowance equal to the | ||
| resource cost. Use the `redeemers` rule to restrict redemption to facilitator addresses from | ||
| the payment requirements. | ||
|
|
||
| See the [`requestExecutionPermissions`](../../../reference/advanced-permissions/wallet-client.md#requestexecutionpermissions) API reference for more information. | ||
|
|
||
| ```ts | ||
| import { base as chain } from 'viem/chains' | ||
|
|
||
| const facilitators = accepted.extra.facilitators | ||
| if (!facilitators || facilitators.length === 0) { | ||
| console.error('No facilitators found in PAYMENT-REQUIRED') | ||
| // Handle error | ||
| } | ||
|
|
||
| const supportedPermissions = await walletClient.getSupportedExecutionPermissions() | ||
|
cursor[bot] marked this conversation as resolved.
Outdated
|
||
| const currentTime = Math.floor(Date.now() / 1000) | ||
| const expiry = currentTime + 3600 | ||
|
|
||
| const grantedPermissions = await walletClient.requestExecutionPermissions([ | ||
| { | ||
| chainId: chain.id, | ||
| expiry, | ||
| to: sessionAccount.address, | ||
| permission: { | ||
| type: 'erc20-token-allowance', | ||
| data: { | ||
| tokenAddress: accepted.asset, | ||
| // Fixed allowance for this resource. | ||
| allowanceAmount: BigInt(accepted.amount), | ||
| justification: 'Permission to pay for a specific x402-protected API resource', | ||
| }, | ||
| isAdjustmentAllowed: false, | ||
| }, | ||
| rules: [ | ||
| { | ||
| type: 'redeemers', | ||
| data: { | ||
| addresses: facilitators!, | ||
| }, | ||
| }, | ||
| ], | ||
| }, | ||
| ]) | ||
| ``` | ||
|
|
||
| ### 5. Create a redelegation | ||
|
|
||
| The granted advanced permission is delegated to the session account. To let facilitator addresses | ||
| redeem this permission context for x402 settlement, create an open redelegation from the session account. | ||
|
AyushBherwani1998 marked this conversation as resolved.
Outdated
|
||
|
|
||
| Use the Wallet Client's [`redelegatePermissionContextOpen`](../../../reference/erc7710/wallet-client.md#redelegatepermissioncontextopen) | ||
| action to create a redelegated permission context. The granted permission already includes | ||
| a [redeemer enforcer](../../../reference/delegation/caveats.md#redeemer), so you do not add extra caveats here. | ||
|
|
||
| <Tabs> | ||
| <TabItem value="example.ts"> | ||
|
|
||
| ```ts | ||
| import { environment, sessionAccountWalletClient } from './config.ts' | ||
|
|
||
| const permission = grantedPermissions[0] | ||
| if (!permission) { | ||
| console.error('No permission response returned by requestExecutionPermissions') | ||
| // Handle error | ||
| } | ||
|
|
||
| const { permissionContext: redelegatedPermissionContext } = | ||
| await sessionAccountWalletClient.redelegatePermissionContextOpen({ | ||
| environment, | ||
| permissionContext: permission!.context, | ||
| }) | ||
| ``` | ||
|
|
||
| </TabItem> | ||
| <TabItem value="config.ts"> | ||
|
|
||
| ```ts | ||
| import { createWalletClient, http } from 'viem' | ||
| import { base as chain } from 'viem/chains' | ||
| import { getSmartAccountsEnvironment } from '@metamask/smart-accounts-kit' | ||
| import { erc7710WalletActions } from '@metamask/smart-accounts-kit/actions' | ||
| import { sessionAccount } from './session-account.ts' | ||
|
|
||
| export const environment = getSmartAccountsEnvironment(chain.id) | ||
|
|
||
| export const sessionAccountWalletClient = createWalletClient({ | ||
| account: sessionAccount, | ||
| chain, | ||
| transport: http(), | ||
| }).extend(erc7710WalletActions()) | ||
| ``` | ||
|
|
||
| </TabItem> | ||
| </Tabs> | ||
|
|
||
| ### 6. Create the payment payload | ||
|
|
||
| Create a payment payload using the redelegated permission context and accepted requirements. | ||
| For ERC-7710 (Smart Contract Delegation), x402 requires the payload fields `delegationManager`, | ||
| `permissionContext`, and `delegator`. The facilitator uses `permissionContext` to simulate | ||
| during verification and then settle the payment. | ||
|
|
||
| Encode the full payment payload as base64, then send it in the payment signature header. | ||
|
|
||
| <Tabs> | ||
| <TabItem value="example.ts"> | ||
|
|
||
| ```ts | ||
| import { PaymentPayload } from './types' | ||
|
|
||
| const permission = grantedPermissions[0] | ||
|
|
||
| const paymentPayload: PaymentPayload = { | ||
| x402Version: 2, | ||
| accepted, | ||
| payload: { | ||
| delegationManager: permission.delegationManager, | ||
| permissionContext: redelegatedPermissionContext, | ||
| delegator: permission.from, | ||
| }, | ||
| } | ||
|
|
||
| const encodedPayment = Buffer.from(JSON.stringify(paymentPayload)).toString('base64') | ||
| ``` | ||
|
|
||
| </TabItem> | ||
| <TabItem value="types.ts"> | ||
|
|
||
| ```ts | ||
| import { Address, Hex } from 'viem' | ||
|
|
||
| export type PaymentPayload = { | ||
| x402Version: 2 | ||
| accepted: PaymentRequirements | ||
| payload: { | ||
| delegationManager: Address | ||
| permissionContext: Hex | ||
| delegator: Address | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| </TabItem> | ||
| </Tabs> | ||
|
|
||
| ### 7. Make the paid request | ||
|
|
||
| Send the base64 encoded payload in the payment signature header. If verification succeeds, the server returns the protected data. | ||
|
|
||
| ```ts | ||
| const apiResponse = await fetch('https://api.example.com/paid-endpoint', { | ||
| headers: { | ||
| 'payment-signature': encodedPayment, | ||
| }, | ||
| }) | ||
|
|
||
| if (!apiResponse.ok) { | ||
| const errorBody = await apiResponse.json() | ||
| console.error(errorBody.error ?? 'API request failed') | ||
| // Handle error | ||
| } | ||
|
|
||
| const data = await apiResponse.json() | ||
| console.log('Protected API response:', data) | ||
| ``` | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.