okx-x402-payment
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOnchain OS x402 Payment
Onchain OS x402 支付
Sign an x402 payment authorization and return the payment proof for accessing payment-gated resources. Supports TEE signing (via wallet session) or local signing (with user's own private key).
签署x402支付授权并返回支付凭证,用于访问付费墙资源,支持通过TEE签名(借助钱包会话)或本地签名(使用用户自身私钥)。
Pre-flight Checks
预执行检查
Every time before running any command, always follow these steps in order. Do not echo routine command output to the user; only provide a brief status update when installing, updating, or handling a failure.
onchainos-
Resolve latest stable version: Fetch the latest stable release tag from the GitHub API:
curl -sSL "https://api.github.com/repos/okx/onchainos-skills/releases/latest"Extract thefield (e.g.,tag_name) intov1.0.5. If the API call fails andLATEST_TAGis already installed locally, skip steps 2-3 and proceed to run the command (the user may be offline or rate-limited; a stale binary is better than blocking). Ifonchainosis not installed, stop and tell the user to check their network connection or install manually from https://github.com/okx/onchainos-skills.onchainos -
Install or update: Ifis not found, or if the cache at
onchainos(~/.onchainos/last_checkon Windows) is older than 12 hours:$env:USERPROFILE\.onchainos\last_check- Download the installer and its checksum file from the latest release tag:
- macOS/Linux:
curl -sSL "https://raw.githubusercontent.com/okx/onchainos-skills/${LATEST_TAG}/install.sh" -o /tmp/onchainos-install.shcurl -sSL "https://github.com/okx/onchainos-skills/releases/download/${LATEST_TAG}/installer-checksums.txt" -o /tmp/installer-checksums.txt - Windows:
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/okx/onchainos-skills/${LATEST_TAG}/install.ps1" -OutFile "$env:TEMP\onchainos-install.ps1"Invoke-WebRequest -Uri "https://github.com/okx/onchainos-skills/releases/download/${LATEST_TAG}/installer-checksums.txt" -OutFile "$env:TEMP\installer-checksums.txt"
- macOS/Linux:
- Verify the installer's SHA256 against . On mismatch, stop and warn — the installer may have been tampered with.
installer-checksums.txt - Execute: (or
sh /tmp/onchainos-install.shon Windows). The installer handles version comparison internally and only downloads the binary if needed.& "$env:TEMP\onchainos-install.ps1" - On other failures, point to https://github.com/okx/onchainos-skills.
- Download the installer and its checksum file from the latest release tag:
-
Verify binary integrity (once per session): Runto get the installed version (e.g.,
onchainos --versionor1.0.5). Construct the installed tag as2.0.0-beta.0. Downloadv<version>for the installed version's tag (not necessarily LATEST_TAG):checksums.txtLook up the platform target and compare the installed binary's SHA256 against the checksum. On mismatch, reinstall (step 2) and re-verify. If still mismatched, stop and warn.curl -sSL "https://github.com/okx/onchainos-skills/releases/download/v<version>/checksums.txt" -o /tmp/onchainos-checksums.txt- Platform targets — macOS: ->
arm64,aarch64-apple-darwin->x86_64; Linux:x86_64-apple-darwin->x86_64,x86_64-unknown-linux-gnu->aarch64,aarch64-unknown-linux-gnu->i686,i686-unknown-linux-gnu->armv7l; Windows:armv7-unknown-linux-gnueabihf->AMD64,x86_64-pc-windows-msvc->x86,i686-pc-windows-msvc->ARM64aarch64-pc-windows-msvc - Hash command — macOS/Linux: ; Windows:
shasum -a 256 ~/.local/bin/onchainos(Get-FileHash "$env:USERPROFILE\.local\bin\onchainos.exe" -Algorithm SHA256).Hash.ToLower()
- Platform targets — macOS:
-
Check for skill version drift (once per session): Ifis newer than this skill's
onchainos --version, display a one-time notice that the skill may be outdated and suggest the user re-install skills via their platform's method. Do not block.metadata.version -
Do NOT auto-reinstall on command failures. Report errors and suggestor manual reinstallation from https://github.com/okx/onchainos-skills.
onchainos --version -
Rate limit errors. If a command hits rate limits, the shared API key may be throttled. Suggest creating a personal key at the OKX Developer Portal. If the user creates afile, remind them to add
.envto.env..gitignore
每次运行任何命令前,请务必按以下步骤操作。无需向用户回显常规命令输出;仅在安装、更新或处理失败时提供简要状态更新。
onchainos-
获取最新稳定版本:从GitHub API获取最新稳定版本标签:
curl -sSL "https://api.github.com/repos/okx/onchainos-skills/releases/latest"提取字段(例如tag_name)并赋值给v1.0.5。 如果API调用失败且本地已安装LATEST_TAG,则跳过步骤2-3,直接运行命令(用户可能处于离线状态或触发了速率限制;使用旧版本二进制文件总比阻塞操作要好)。如果未安装onchainos,则停止操作并告知用户检查网络连接,或从https://github.com/okx/onchainos-skills手动安装。onchainos -
安装或更新:如果未找到,或本地缓存
onchainos(Windows系统为~/.onchainos/last_check)的更新时间超过12小时:$env:USERPROFILE\.onchainos\last_check- 从最新版本标签下载安装程序及其校验和文件:
- macOS/Linux:
curl -sSL "https://raw.githubusercontent.com/okx/onchainos-skills/${LATEST_TAG}/install.sh" -o /tmp/onchainos-install.shcurl -sSL "https://github.com/okx/onchainos-skills/releases/download/${LATEST_TAG}/installer-checksums.txt" -o /tmp/installer-checksums.txt - Windows:
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/okx/onchainos-skills/${LATEST_TAG}/install.ps1" -OutFile "$env:TEMP\onchainos-install.ps1"Invoke-WebRequest -Uri "https://github.com/okx/onchainos-skills/releases/download/${LATEST_TAG}/installer-checksums.txt" -OutFile "$env:TEMP\installer-checksums.txt"
- macOS/Linux:
- 验证安装程序的SHA256哈希值是否与中的一致。如果不匹配,停止操作并发出警告——安装程序可能已被篡改。
installer-checksums.txt - 执行安装:(Windows系统为
sh /tmp/onchainos-install.sh)。 安装程序会自动处理版本比较,仅在需要时下载二进制文件。& "$env:TEMP\onchainos-install.ps1" - 如果安装失败,请引导用户访问https://github.com/okx/onchainos-skills。
- 从最新版本标签下载安装程序及其校验和文件:
-
验证二进制文件完整性(每会话一次):运行获取已安装版本(例如
onchainos --version或1.0.5)。将已安装版本构造成标签格式2.0.0-beta.0。 下载已安装版本标签的v<version>文件(不一定是最新版本标签):checksums.txt查找对应平台的目标文件,比较已安装二进制文件的SHA256哈希值与校验和。 如果不匹配,重新执行步骤2并再次验证。如果仍然不匹配,停止操作并发出警告。curl -sSL "https://github.com/okx/onchainos-skills/releases/download/v<version>/checksums.txt" -o /tmp/onchainos-checksums.txt- 平台目标映射 —— macOS:→
arm64,aarch64-apple-darwin→x86_64;Linux:x86_64-apple-darwin→x86_64,x86_64-unknown-linux-gnu→aarch64,aarch64-unknown-linux-gnu→i686,i686-unknown-linux-gnu→armv7l;Windows:armv7-unknown-linux-gnueabihf→AMD64,x86_64-pc-windows-msvc→x86,i686-pc-windows-msvc→ARM64aarch64-pc-windows-msvc - 哈希计算命令 —— macOS/Linux:;Windows:
shasum -a 256 ~/.local/bin/onchainos(Get-FileHash "$env:USERPROFILE\.local\bin\onchainos.exe" -Algorithm SHA256).Hash.ToLower()
- 平台目标映射 —— macOS:
-
检查技能版本漂移(每会话一次):如果显示的版本高于本技能的
onchainos --version,则一次性通知用户该技能可能已过时,并建议用户通过对应平台的方法重新安装技能。无需阻塞操作。metadata.version -
命令失败时请勿自动重新安装。报告错误并建议用户执行或从https://github.com/okx/onchainos-skills手动重新安装。
onchainos --version
Skill Routing
技能路由
- For querying authenticated wallet balance / send tokens / tx history → use
okx-agentic-wallet - For querying public wallet balance (by address) → use
okx-wallet-portfolio - For token swaps / trades / buy / sell → use
okx-dex-swap - For token search / metadata / rankings / holder info / cluster analysis → use
okx-dex-token - For token prices / K-line charts / wallet PnL / address tracker activities → use
okx-dex-market - For smart money / whale / KOL signals / leaderboard → use
okx-dex-signal - For meme / pump.fun token scanning → use
okx-dex-trenches - For transaction broadcasting / gas estimation → use
okx-onchain-gateway - For security scanning (token / DApp / tx / signature) → use
okx-security
- 查询已认证钱包余额/发送代币/交易历史 → 使用
okx-agentic-wallet - 查询公开钱包余额(通过地址) → 使用
okx-wallet-portfolio - 代币兑换/交易/买入/卖出 → 使用
okx-dex-swap - 代币搜索/元数据/排名/持有者信息/集群分析 → 使用
okx-dex-token - 代币价格/K线图/钱包盈亏/地址追踪活动 → 使用
okx-dex-market - 聪明资金/鲸鱼/KOL信号/排行榜 → 使用
okx-dex-signal - Meme/pump.fun代币扫描 → 使用
okx-dex-trenches - 交易广播/燃气费估算 → 使用
okx-onchain-gateway - 安全扫描(代币/DApp/交易/签名) → 使用
okx-security
Chain Name Support
支持的链名称
--networkeip155:<realChainIndex>onchainos wallet chainsrealChainIndex<chainId>Common examples:
| Chain | Network Identifier |
|---|---|
| Ethereum | |
| X Layer | |
| Base | |
| Arbitrum One | |
| Linea | |
For the full list of supported EVM chains and their , run:
realChainIndexbash
onchainos wallet chainsNon-EVM chains (e.g., Solana, Tron, Ton, Sui) are not supported by x402 payment — onlyidentifiers are accepted.eip155:*
--networkeip155:<realChainIndex>onchainos wallet chainsrealChainIndex<chainId>常见示例:
| 链名称 | 网络标识符 |
|---|---|
| Ethereum | |
| X Layer | |
| Base | |
| Arbitrum One | |
| Linea | |
要查看所有支持的EVM链及其,运行:
realChainIndexbash
onchainos wallet chains非EVM链(例如Solana、Tron、Ton、Sui)不支持x402支付 —— 仅接受格式的标识符。eip155:*
Background: x402 Protocol
背景:x402协议
x402 is an HTTP payment protocol. When a server returns , it includes a base64-encoded JSON payload describing what payment is required. The full flow is:
HTTP 402 Payment Required- Send request → receive with base64-encoded payment payload
HTTP 402 - Decode the payload, extract payment parameters from
accepts[0] - Sign via TEE → → obtain
onchainos payment x402-pay{ signature, authorization } - Assemble payment header and replay the original request
This skill owns steps 2–4 end to end.
x402是一种HTTP支付协议。当服务器返回响应时,会包含一个base64编码的JSON负载,描述所需的支付信息。完整流程如下:
HTTP 402 Payment Required- 发送请求 → 收到响应及base64编码的支付负载
HTTP 402 - 解码负载,从中提取支付参数
accepts[0] - 通过TEE签名 → → 获取
onchainos payment x402-pay{ signature, authorization } - 组装支付头并重试原请求
本技能负责步骤2-4的全流程。
Quickstart
快速开始
bash
undefinedbash
undefinedSign an x402 payment for an X Layer USDG-gated resource
为X Layer网络上USDG付费墙资源签署x402支付
onchainos payment x402-pay
--network eip155:196
--amount 1000000
--pay-to 0xRecipientAddress
--asset 0x4ae46a509f6b1d9056937ba4500cb143933d2dc8
--max-timeout-seconds 300
--network eip155:196
--amount 1000000
--pay-to 0xRecipientAddress
--asset 0x4ae46a509f6b1d9056937ba4500cb143933d2dc8
--max-timeout-seconds 300
undefinedonchainos payment x402-pay
--network eip155:196
--amount 1000000
--pay-to 0xRecipientAddress
--asset 0x4ae46a509f6b1d9056937ba4500cb143933d2dc8
--max-timeout-seconds 300
--network eip155:196
--amount 1000000
--pay-to 0xRecipientAddress
--asset 0x4ae46a509f6b1d9056937ba4500cb143933d2dc8
--max-timeout-seconds 300
undefinedCommand Index
命令索引
| # | Command | Description |
|---|---|---|
| 1 | | Sign an x402 payment and return the payment proof |
| 序号 | 命令 | 描述 |
|---|---|---|
| 1 | | 签署x402支付并返回支付凭证 |
Operation Flow
操作流程
Step 1: Send the Original Request
步骤1:发送原请求
Make the HTTP request the user asked for. If the response status is not 402, return the result directly — no payment needed, do not check wallet or attempt login.
IMPORTANT: Do NOT check wallet status or attempt login before sending the request. Only proceed to payment steps if the response is HTTP 402.
执行用户要求的HTTP请求。如果响应状态码不是402,直接返回结果 —— 无需支付,请勿检查钱包或尝试登录。
重要提示:发送请求前请勿检查钱包状态或尝试登录。仅当响应为HTTP 402时,才进入支付流程。
Step 2: Decode the 402 Payload
步骤2:解码402负载
If the response is , the body is a base64-encoded JSON string. Decode it:
HTTP 402rawBody = response.body // base64 string
decoded = JSON.parse(atob(rawBody))
option = decoded.accepts[0]Extract these fields from :
option| x402 field | CLI param | Notes |
|---|---|---|
| | CAIP-2 format, e.g. |
| | prefer |
| | |
| | token contract address |
| | optional, default 300 |
⚠️ MANDATORY: Display payment details and STOP to wait for user confirmation. Do NOT check wallet status, run , attempt login, or call any other tool until the user explicitly confirms.
onchainos wallet statusPresent the following information to the user:
This resource requires x402 payment:
- Network:
(<chain name>)<network>- Token:
(<token symbol>)<asset>- Amount:
(convert from minimal units using token decimals)<human-readable amount>- Pay to:
<payTo>Proceed with payment? (yes / no)
Then STOP and wait for the user's response. Do not proceed in the same turn.
- User confirms → proceed to Step 3.
- User declines → stop immediately, no payment is made, no wallet check.
如果响应为,响应体是一个base64编码的JSON字符串。解码该字符串:
HTTP 402rawBody = response.body // base64字符串
decoded = JSON.parse(atob(rawBody))
option = decoded.accepts[0]从中提取以下字段:
option| x402字段 | CLI参数 | 说明 |
|---|---|---|
| | CAIP-2格式,例如 |
| | 优先使用 |
| | |
| | 代币合约地址 |
| | 可选参数,默认值300 |
⚠️ 强制要求:显示支付详情并停止操作,等待用户确认。在用户明确确认前,请勿检查钱包状态、运行、尝试登录或调用任何其他工具。
onchainos wallet status向用户展示以下信息:
该资源需要x402支付:
- 网络:
(<链名称>)<network>- 代币:
(<代币符号>)<asset>- 金额:
(使用代币小数位数从最小单位转换)<人类可读金额>- 收款地址:
<payTo>是否继续支付?(是/否)
然后停止操作,等待用户回复。请勿在同一轮对话中继续执行。
- 用户确认 → 进入步骤3。
- 用户拒绝 → 立即停止操作,不进行支付。
Step 3: Check Wallet Status (only after user explicitly confirms payment)
步骤3:检查钱包状态(仅在用户明确确认支付后执行)
Now that payment is required, check if the user has a wallet session:
bash
onchainos wallet status- Logged in → proceed to Step 4 (Sign).
- Not logged in → ask the user:
"This resource requires payment (x402). You need a wallet to sign the payment. Would you like to create one? (It's free and takes ~30 seconds.)"
- User says yes → run (AK login, no email) or
onchainos wallet login(OTP login), then proceed to Step 4.onchainos wallet login <email> - User says no → switch to the Local Signing Fallback (see below).
确认需要支付后,检查用户是否有活跃的钱包会话:
bash
onchainos wallet status- 已登录 → 进入步骤4(签名)。
- 未登录 → 询问用户:
"该资源需要x402支付。您需要一个钱包来签署支付信息。是否需要创建一个钱包?(免费,约30秒即可完成。)"
- 用户同意 → 运行(AK登录,无需邮箱)或
onchainos wallet login(OTP登录),然后进入步骤4。onchainos wallet login <email> - 用户拒绝 → 切换到本地签名回退流程(见下文)。
Step 4: Sign
步骤4:签名
Run with the extracted parameters. Returns .
onchainos payment x402-pay{ signature, authorization }If signing fails (e.g., session expired, not logged in, AK re-login failed):
- Do NOT simply cancel or give up.
- Ask the user: "Signing failed because there is no active wallet session. Would you like to log in now, or sign locally with your own private key?"
- User wants to log in → run or
onchainos wallet login, then retry this step.onchainos wallet login <email> - User wants local signing → switch to the Local Signing Fallback (see below).
- User wants to cancel → only then cancel the request.
- User wants to log in → run
使用提取的参数运行。返回。
onchainos payment x402-pay{ signature, authorization }如果签名失败(例如会话过期、未登录、AK重新登录失败):
- 请勿直接取消或放弃操作。
- 询问用户:"签名失败,原因是没有活跃的钱包会话。您现在是否要登录,或者使用自身私钥进行本地签名?"
- 用户选择登录 → 运行或
onchainos wallet login,然后重试本步骤。onchainos wallet login <email> - 用户选择本地签名 → 切换到本地签名回退流程(见下文)。
- 用户选择取消 → 此时才取消请求。
- 用户选择登录 → 运行
Step 5: Assemble Header and Replay
步骤5:组装支付头并重试请求
Determine header name from :
decoded.x402Version- →
x402Version >= 2PAYMENT-SIGNATURE - (or absent) →
x402Version < 2X-PAYMENT
Build header value:
paymentPayload = { ...decoded, payload: { signature, authorization } }
headerValue = btoa(JSON.stringify(paymentPayload))Replay the original request with the header attached:
GET/POST <original-url>
<header-name>: <headerValue>Return the final response body to the user.
根据确定头名称:
decoded.x402Version- →
x402Version >= 2PAYMENT-SIGNATURE - (或未设置) →
x402Version < 2X-PAYMENT
构建头值:
paymentPayload = { ...decoded, payload: { signature, authorization } }
headerValue = btoa(JSON.stringify(paymentPayload))重试原请求并附加支付头:
GET/POST <原URL>
<header-name>: <headerValue>将最终响应体返回给用户。
Step 6: Suggest Next Steps
步骤6:建议后续操作
After a successful payment and response, suggest:
| Just completed | Suggest |
|---|---|
| Successful replay | 1. Check balance impact → |
| 402 on replay (expired) | Retry from Step 4 with a fresh signature |
Present conversationally, e.g.: "Done! The resource returned the following result. Would you like to check your updated balance?" — never expose skill names or internal field names to the user.
支付成功并返回响应后,向用户建议以下操作:
| 刚完成的操作 | 建议操作 |
|---|---|
| 请求重试成功 | 1. 查看余额变化 → 使用 |
| 重试时返回402(凭证过期) | 从步骤4重新开始,获取新的签名 |
以对话形式呈现,例如:"操作完成!该资源已返回结果。是否需要查看您更新后的钱包余额?" —— 请勿向用户暴露技能名称或内部字段名称。
Cross-Skill Workflows
跨技能工作流
Workflow A: Pay for a 402-Gated API Resource (most common)
工作流A:为402付费墙API资源支付(最常见)
User: "Fetch https://api.example.com/data — it requires x402 payment"
1. Send GET https://api.example.com/data → HTTP 402 with base64 payload
↓ decode payload, extract accepts[0]
2. okx-x402-payment onchainos payment x402-pay \
--network eip155:196 --amount 1000000 \
--pay-to 0xAbC... \
--asset 0x4ae46a509f6b1d9056937ba4500cb143933d2dc8 → { signature, authorization }
↓ assemble payment header
3. Replay GET https://api.example.com/data with PAYMENT-SIGNATURE header → HTTP 200Data handoff:
- →
accepts[0].network--network - (or
accepts[0].amount) →maxAmountRequired--amount - →
accepts[0].payTo--pay-to - →
accepts[0].asset--asset
用户:"获取https://api.example.com/data的数据 —— 它需要x402支付"
1. 发送GET https://api.example.com/data → 返回HTTP 402及base64编码的负载
↓ 解码负载,提取accepts[0]
2. okx-x402-payment 运行onchainos payment x402-pay \
--network eip155:196 --amount 1000000 \
--pay-to 0xAbC... \
--asset 0x4ae46a509f6b1d9056937ba4500cb143933d2dc8 → 返回{ signature, authorization }
↓ 组装支付头
3. 附加PAYMENT-SIGNATURE头并重试GET https://api.example.com/data → 返回HTTP 200数据传递:
- →
accepts[0].network--network - (或
accepts[0].amount) →maxAmountRequired--amount - →
accepts[0].payTo--pay-to - →
accepts[0].asset--asset
Workflow B: Pay then Check Balance
工作流B:支付后查看余额
User: "Access this paid API, then show me how much I spent"
1. okx-x402-payment (Workflow A above) → payment proof + successful response
2. okx-agentic-wallet onchainos wallet balance --chain 196 → current balance after payment用户:"访问这个付费API,然后告诉我我花了多少钱"
1. okx-x402-payment 执行工作流A → 返回支付凭证及成功响应
2. okx-agentic-wallet 运行onchainos wallet balance --chain 196 → 返回支付后的当前余额Workflow C: Security Check before Payment
工作流C:支付前进行安全检查
User: "Is this x402 payment safe? The asset is 0x4ae46a..."
1. okx-security onchainos security token-scan \
--address 0x4ae46a509f6b1d9056937ba4500cb143933d2dc8 \
--chain 196 → token risk report
↓ if safe
2. okx-x402-payment (Workflow A above) → sign and pay用户:"这个x402支付安全吗?代币地址是0x4ae46a..."
1. okx-security 运行onchainos security token-scan \
--address 0x4ae46a509f6b1d9056937ba4500cb143933d2dc8 \
--chain 196 → 返回代币风险报告
↓ 如果安全
2. okx-x402-payment 执行工作流A → 签署并支付CLI Command Reference
CLI命令参考
1. onchainos payment x402-pay
1. onchainos payment x402-pay
Sign an x402 payment and return the EIP-3009 payment proof.
bash
onchainos payment x402-pay \
--network <network> \
--amount <amount> \
--pay-to <address> \
--asset <address> \
[--from <address>] \
[--max-timeout-seconds <seconds>]| Param | Required | Default | Description |
|---|---|---|---|
| Yes | - | CAIP-2 network identifier (e.g., |
| Yes | - | Payment amount in minimal units (e.g., |
| Yes | - | Recipient address (from x402 |
| Yes | - | Token contract address (from x402 |
| No | selected account | Payer address; if omitted, uses the currently selected account |
| No | | Authorization validity window in seconds |
Return fields:
| Field | Type | Description |
|---|---|---|
| String | EIP-3009 secp256k1 signature (65 bytes, r+s+v, hex) returned by TEE backend |
| Object | Standard x402 EIP-3009 |
| String | Payer wallet address |
| String | Recipient address (= |
| String | Payment amount in minimal units (= |
| String | Authorization valid-after timestamp (Unix seconds) |
| String | Authorization valid-before timestamp (Unix seconds) |
| String | Random nonce (hex, 32 bytes), prevents replay attacks |
签署x402支付并返回EIP-3009支付凭证。
bash
onchainos payment x402-pay \
--network <network> \
--amount <amount> \
--pay-to <address> \
--asset <address> \
[--from <address>] \
[--max-timeout-seconds <seconds>]| 参数 | 是否必填 | 默认值 | 描述 |
|---|---|---|---|
| 是 | - | CAIP-2格式的网络标识符(例如X Layer为 |
| 是 | - | 支付金额,以最小单位计算(例如 |
| 是 | - | 收款地址(来自x402的 |
| 是 | - | 代币合约地址(来自x402的 |
| 否 | 当前选中的账户 | 付款地址;如果省略,则使用当前选中的账户 |
| 否 | | 授权的有效时长(秒) |
返回字段:
| 字段 | 类型 | 描述 |
|---|---|---|
| 字符串 | TEE后端返回的EIP-3009 secp256k1签名(65字节,格式为r+s+v,十六进制) |
| 对象 | 标准x402 EIP-3009 |
| 字符串 | 付款钱包地址 |
| 字符串 | 收款地址(等于 |
| 字符串 | 支付金额,以最小单位计算(等于402负载中的 |
| 字符串 | 授权生效时间戳(Unix秒级) |
| 字符串 | 授权失效时间戳(Unix秒级) |
| 字符串 | 随机nonce(十六进制,32字节),用于防止重放攻击 |
Input / Output Examples
输入/输出示例
User says: "Fetch https://api.example.com/data — it requires x402 payment"
Step 1 — original request returns 402:
HTTP 402
Body: "eyJ4NDAyVmVyc2lvbiI6MiwiYWNjZXB0cyI6W3s..." ← base64Decoded payload:
json
{
"x402Version": 2,
"accepts": [{
"network": "eip155:196",
"amount": "1000000",
"payTo": "0xAbC...",
"asset": "0x4ae46a509f6b1d9056937ba4500cb143933d2dc8",
"maxTimeoutSeconds": 300
}]
}Step 3–4 — check wallet + sign:
bash
onchainos payment x402-pay \
--network eip155:196 \
--amount 1000000 \
--pay-to 0xAbC... \
--asset 0x4ae46a509f6b1d9056937ba4500cb143933d2dc8 \
--max-timeout-seconds 300用户请求: "获取https://api.example.com/data的数据 —— 它需要x402支付"
步骤1 —— 原请求返回402:
HTTP 402
Body: "eyJ4NDAyVmVyc2lvbiI6MiwiYWNjZXB0cyI6W3s..." ← base64编码解码后的负载:
json
{
"x402Version": 2,
"accepts": [{
"network": "eip155:196",
"amount": "1000000",
"payTo": "0xAbC...",
"asset": "0x4ae46a509f6b1d9056937ba4500cb143933d2dc8",
"maxTimeoutSeconds": 300
}]
}步骤3-4 —— 检查钱包+签名:
bash
onchainos payment x402-pay \
--network eip155:196 \
--amount 1000000 \
--pay-to 0xAbC... \
--asset 0x4ae46a509f6b1d9056937ba4500cb143933d2dc8 \
--max-timeout-seconds 300→ { "signature": "0x...", "authorization": { ... } }
→ 返回{ "signature": "0x...", "authorization": { ... } }
**Step 5** — assemble header and replay:paymentPayload = { ...decoded, payload: { signature, authorization } }
headerValue = btoa(JSON.stringify(paymentPayload))
GET https://api.example.com/data
PAYMENT-SIGNATURE: <headerValue>
→ HTTP 200 { "result": "..." }
undefined
**步骤5** —— 组装支付头并重试:paymentPayload = { ...decoded, payload: { signature, authorization } }
headerValue = btoa(JSON.stringify(paymentPayload))
GET https://api.example.com/data
PAYMENT-SIGNATURE: <headerValue>
→ 返回HTTP 200 { "result": "..." }
undefinedLocal Signing Fallback (No Wallet)
本地签名回退流程(无钱包)
If the user does not have a wallet and chooses not to create one, guide them through local EIP-3009 signing with their own private key.
如果用户没有钱包且不想创建,则引导用户使用自身私钥进行本地EIP-3009签名。
Prerequisites
前提条件
- User has a local private key (e.g., in a file, hardware wallet, or MetaMask export)
.env - The payer address must hold sufficient ERC-20 balance of the token on the target chain
asset - The token contract must support EIP-3009
assettransferWithAuthorization
- 用户拥有本地私钥(例如存储在文件、硬件钱包或从MetaMask导出)
.env - 付款地址在目标链上持有足够的代币ERC-20余额
asset - 代币合约支持EIP-3009
asset方法transferWithAuthorization
Step 1: Decode the 402 Payload
步骤1:解码402负载
Same as the main flow — decode the base64 body and extract :
accepts[0]rawBody = response.body
decoded = JSON.parse(atob(rawBody))
option = decoded.accepts[0]Extract: , (or ), , , .
networkamountmaxAmountRequiredpayToassetmaxTimeoutSeconds与主流程相同 —— 解码base64编码的响应体,提取:
accepts[0]rawBody = response.body
decoded = JSON.parse(atob(rawBody))
option = decoded.accepts[0]提取:、(或)、、、。
networkamountmaxAmountRequiredpayToassetmaxTimeoutSecondsStep 2: Construct EIP-3009 Parameters and Sign
步骤2:构造EIP-3009参数并签名
Build the message and sign it with . Key fields:
TransferWithAuthorizationeth_signTypedData_v4| Field | Value |
|---|---|
| Payer address |
| |
| |
| |
| |
| Random 32 bytes (hex) |
EIP-712 domain: query the token contract's , (often or ), from the CAIP-2 network, and = .
name()version"1""2"chainIdverifyingContractoption.assetSign with ethers.js:
javascript
const wallet = new ethers.Wallet('<PRIVATE_KEY>');
const signature = await wallet.signTypedData(domain, types, message);See EIP-3009 for the full typed data spec./domain.namevary per token (e.g. USDC usesversion/"USD Coin") — query the contract to confirm."2"
构建消息,使用进行签名。关键字段:
TransferWithAuthorizationeth_signTypedData_v4| 字段 | 值 |
|---|---|
| 付款地址 |
| |
| |
| |
| |
| 随机32字节十六进制值 |
EIP-712域:查询代币合约的、(通常为或)、从CAIP-2网络中获取, = 。
name()version"1""2"chainIdverifyingContractoption.asset使用ethers.js签名:
javascript
const wallet = new ethers.Wallet('<PRIVATE_KEY>');
const signature = await wallet.signTypedData(domain, types, message);Step 3: Assemble Header and Replay
步骤3:组装支付头并重试
Same as the main flow Step 5 — build from the signed fields, determine header name from , assemble , base64-encode, and replay the original request with the payment header attached.
authorizationx402VersionpaymentPayload = { ...decoded, payload: { signature, authorization } }与主流程步骤5相同 —— 从签名字段构建,根据确定头名称,组装,进行base64编码,然后附加支付头并重试原请求。
authorizationx402VersionpaymentPayload = { ...decoded, payload: { signature, authorization } }Important Notes for Local Signing
本地签名的重要注意事项
- The private key never leaves the local machine — signing is done entirely offline
- The must be a random 32-byte hex value; reusing a nonce will cause the transaction to be rejected
nonce - is a Unix timestamp in seconds — set it to
validBefore(default 300s / 5 minutes)now + maxTimeoutSeconds - If the token uses a non-standard EIP-712 domain (e.g., different string), the signature will be invalid — always query the contract first
version - The signed authorization only authorizes the exact tuple — it cannot be modified or reused
(from, to, value, nonce)
- 私钥永远不会离开本地机器 —— 签名完全离线完成
- 必须是随机的32字节十六进制值;重复使用nonce会导致交易被拒绝
nonce - 是Unix秒级时间戳 —— 设置为
validBefore(默认300秒/5分钟)当前时间 + maxTimeoutSeconds - 如果代币使用非标准EIP-712域(例如不同的字符串),签名将无效 —— 请务必先查询合约
version - 已签署的授权仅对精确的元组有效 —— 无法修改或重复使用
(from, to, value, nonce)
Edge Cases
边缘情况
- Not logged in: Ask user if they want to create a wallet (or
onchainos wallet login). If not, guide them through the Local Signing Fallback aboveonchainos wallet login <email> - Unsupported network: Only EVM chains with CAIP-2 format are supported
eip155:<chainId> - No wallet for chain: The logged-in account must have an address on the requested chain; if not, inform the user
- Amount in wrong units: must be in minimal units — remind user to convert (e.g., 1 USDG =
--amountfor 6 decimals)1000000 - Expired authorization: If the server rejects the payment as expired, retry with a fresh signature
- Network error: Retry once, then prompt user to try again later
- 未登录:询问用户是否要创建钱包(或
onchainos wallet login)。如果用户拒绝,则引导其使用本地签名回退流程onchainos wallet login <email> - 不支持的网络:仅支持CAIP-2格式为的EVM链
eip155:<chainId> - 目标链无钱包:已登录的账户必须在目标链上拥有地址;如果没有,告知用户
- 金额单位错误:必须以最小单位计算 —— 提醒用户进行转换(例如1 USDG =
--amount,小数位数为6)1000000 - 授权过期:如果服务器拒绝支付并提示过期,则重新执行步骤4获取新签名
- 网络错误:重试一次,然后提示用户稍后再试
Amount Display Rules
金额显示规则
- is always in minimal units (e.g.,
--amountfor 1 USDG)1000000 - When displaying to the user, convert to UI units: divide by
10^decimal - Show token symbol alongside (e.g., )
1.00 USDG
- 始终以最小单位计算(例如1 USDG对应
--amount)1000000 - 向用户显示时,转换为可读单位:除以
10^decimal - 同时显示代币符号(例如)
1.00 USDG
Global Notes
全局说明
- Primary path (): requires an authenticated JWT session; signing is performed inside a TEE — the private key never leaves the secure enclave
onchainos payment x402-pay - Fallback path (local signing): requires the user's own private key; signing is done entirely on the local machine — no JWT or TEE needed
- This skill only signs — it does not broadcast or deduct balance directly; payment settles when the recipient redeems the authorization on-chain
- must be CAIP-2 format:
--network(e.g.,eip155:<chainId>,eip155:1,eip155:8453)eip155:196 - The returned object must be included alongside
authorizationwhen building the payment headersignature
- 主路径():需要已认证的JWT会话;签名在TEE内部执行 —— 私钥永远不会离开安全飞地
onchainos payment x402-pay - 回退路径(本地签名):需要用户自身的私钥;签名完全在本地机器上完成 —— 无需JWT或TEE
- 本技能仅负责签名 —— 不直接广播交易或扣除余额;当收款方在链上兑现授权时,支付才会完成
- 必须为CAIP-2格式:
--network(例如eip155:<chainId>、eip155:1、eip155:8453)eip155:196 - 返回的对象必须与
authorization一起包含在支付头中signature