okx-x402-payment

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Onchain 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
onchainos
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.
  1. 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 the
    tag_name
    field (e.g.,
    v1.0.5
    ) into
    LATEST_TAG
    . If the API call fails and
    onchainos
    is 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). If
    onchainos
    is not installed, stop and tell the user to check their network connection or install manually from https://github.com/okx/onchainos-skills.
  2. Install or update: If
    onchainos
    is not found, or if the cache at
    ~/.onchainos/last_check
    (
    $env:USERPROFILE\.onchainos\last_check
    on Windows) is older than 12 hours:
    • 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.sh
        curl -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"
    • Verify the installer's SHA256 against
      installer-checksums.txt
      . On mismatch, stop and warn — the installer may have been tampered with.
    • Execute:
      sh /tmp/onchainos-install.sh
      (or
      & "$env:TEMP\onchainos-install.ps1"
      on Windows). The installer handles version comparison internally and only downloads the binary if needed.
    • On other failures, point to https://github.com/okx/onchainos-skills.
  3. Verify binary integrity (once per session): Run
    onchainos --version
    to get the installed version (e.g.,
    1.0.5
    or
    2.0.0-beta.0
    ). Construct the installed tag as
    v<version>
    . Download
    checksums.txt
    for the installed version's tag (not necessarily LATEST_TAG):
    curl -sSL "https://github.com/okx/onchainos-skills/releases/download/v<version>/checksums.txt" -o /tmp/onchainos-checksums.txt
    Look 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.
    • Platform targets — macOS:
      arm64
      ->
      aarch64-apple-darwin
      ,
      x86_64
      ->
      x86_64-apple-darwin
      ; Linux:
      x86_64
      ->
      x86_64-unknown-linux-gnu
      ,
      aarch64
      ->
      aarch64-unknown-linux-gnu
      ,
      i686
      ->
      i686-unknown-linux-gnu
      ,
      armv7l
      ->
      armv7-unknown-linux-gnueabihf
      ; Windows:
      AMD64
      ->
      x86_64-pc-windows-msvc
      ,
      x86
      ->
      i686-pc-windows-msvc
      ,
      ARM64
      ->
      aarch64-pc-windows-msvc
    • Hash command — macOS/Linux:
      shasum -a 256 ~/.local/bin/onchainos
      ; Windows:
      (Get-FileHash "$env:USERPROFILE\.local\bin\onchainos.exe" -Algorithm SHA256).Hash.ToLower()
  4. Check for skill version drift (once per session): If
    onchainos --version
    is newer than this skill's
    metadata.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.
  5. Do NOT auto-reinstall on command failures. Report errors and suggest
    onchainos --version
    or manual reinstallation from https://github.com/okx/onchainos-skills.
  6. 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 a
    .env
    file, remind them to add
    .env
    to
    .gitignore
    .
每次运行任何
onchainos
命令前,请务必按以下步骤操作。无需向用户回显常规命令输出;仅在安装、更新或处理失败时提供简要状态更新。
  1. 获取最新稳定版本:从GitHub API获取最新稳定版本标签:
    curl -sSL "https://api.github.com/repos/okx/onchainos-skills/releases/latest"
    提取
    tag_name
    字段(例如
    v1.0.5
    )并赋值给
    LATEST_TAG
    。 如果API调用失败且本地已安装
    onchainos
    ,则跳过步骤2-3,直接运行命令(用户可能处于离线状态或触发了速率限制;使用旧版本二进制文件总比阻塞操作要好)。如果未安装
    onchainos
    ,则停止操作并告知用户检查网络连接,或从https://github.com/okx/onchainos-skills手动安装。
  2. 安装或更新:如果未找到
    onchainos
    ,或本地缓存
    ~/.onchainos/last_check
    (Windows系统为
    $env:USERPROFILE\.onchainos\last_check
    )的更新时间超过12小时:
    • 从最新版本标签下载安装程序及其校验和文件:
      • macOS/Linux
        curl -sSL "https://raw.githubusercontent.com/okx/onchainos-skills/${LATEST_TAG}/install.sh" -o /tmp/onchainos-install.sh
        curl -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"
    • 验证安装程序的SHA256哈希值是否与
      installer-checksums.txt
      中的一致。如果不匹配,停止操作并发出警告——安装程序可能已被篡改。
    • 执行安装:
      sh /tmp/onchainos-install.sh
      (Windows系统为
      & "$env:TEMP\onchainos-install.ps1"
      )。 安装程序会自动处理版本比较,仅在需要时下载二进制文件。
    • 如果安装失败,请引导用户访问https://github.com/okx/onchainos-skills。
  3. 验证二进制文件完整性(每会话一次):运行
    onchainos --version
    获取已安装版本(例如
    1.0.5
    2.0.0-beta.0
    )。将已安装版本构造成标签格式
    v<version>
    。 下载已安装版本标签
    checksums.txt
    文件(不一定是最新版本标签):
    curl -sSL "https://github.com/okx/onchainos-skills/releases/download/v<version>/checksums.txt" -o /tmp/onchainos-checksums.txt
    查找对应平台的目标文件,比较已安装二进制文件的SHA256哈希值与校验和。 如果不匹配,重新执行步骤2并再次验证。如果仍然不匹配,停止操作并发出警告。
    • 平台目标映射 —— macOS:
      arm64
      aarch64-apple-darwin
      x86_64
      x86_64-apple-darwin
      ;Linux:
      x86_64
      x86_64-unknown-linux-gnu
      aarch64
      aarch64-unknown-linux-gnu
      i686
      i686-unknown-linux-gnu
      armv7l
      armv7-unknown-linux-gnueabihf
      ;Windows:
      AMD64
      x86_64-pc-windows-msvc
      x86
      i686-pc-windows-msvc
      ARM64
      aarch64-pc-windows-msvc
    • 哈希计算命令 —— macOS/Linux:
      shasum -a 256 ~/.local/bin/onchainos
      ;Windows:
      (Get-FileHash "$env:USERPROFILE\.local\bin\onchainos.exe" -Algorithm SHA256).Hash.ToLower()
  4. 检查技能版本漂移(每会话一次):如果
    onchainos --version
    显示的版本高于本技能的
    metadata.version
    ,则一次性通知用户该技能可能已过时,并建议用户通过对应平台的方法重新安装技能。无需阻塞操作。
  5. 命令失败时请勿自动重新安装。报告错误并建议用户执行
    onchainos --version
    或从https://github.com/okx/onchainos-skills手动重新安装。
  6. 速率限制错误处理:如果命令触发速率限制,说明共享API密钥可能已被限流。建议用户在OKX开发者门户创建个人密钥。如果用户创建了
    .env
    文件,提醒他们将
    .env
    添加到
    .gitignore
    中。

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

支持的链名称

--network
uses CAIP-2 format:
eip155:<realChainIndex>
. All EVM chains returned by
onchainos wallet chains
are supported. The
realChainIndex
field in the chain list corresponds to the
<chainId>
portion of the CAIP-2 identifier.
Common examples:
ChainNetwork Identifier
Ethereum
eip155:1
X Layer
eip155:196
Base
eip155:8453
Arbitrum One
eip155:42161
Linea
eip155:59144
For the full list of supported EVM chains and their
realChainIndex
, run:
bash
onchainos wallet chains
Non-EVM chains (e.g., Solana, Tron, Ton, Sui) are not supported by x402 payment — only
eip155:*
identifiers are accepted.
--network
参数使用CAIP-2格式:
eip155:<realChainIndex>
onchainos wallet chains
返回的所有EVM链均受支持。链列表中的
realChainIndex
字段对应CAIP-2标识符中的
<chainId>
部分。
常见示例:
链名称网络标识符
Ethereum
eip155:1
X Layer
eip155:196
Base
eip155:8453
Arbitrum One
eip155:42161
Linea
eip155:59144
要查看所有支持的EVM链及其
realChainIndex
,运行:
bash
onchainos wallet chains
非EVM链(例如Solana、Tron、Ton、Sui)不支持x402支付 —— 仅接受
eip155:*
格式的标识符。

Background: x402 Protocol

背景:x402协议

x402 is an HTTP payment protocol. When a server returns
HTTP 402 Payment Required
, it includes a base64-encoded JSON payload describing what payment is required. The full flow is:
  1. Send request → receive
    HTTP 402
    with base64-encoded payment payload
  2. Decode the payload, extract payment parameters from
    accepts[0]
  3. Sign via TEE →
    onchainos payment x402-pay
    → obtain
    { signature, authorization }
  4. Assemble payment header and replay the original request
This skill owns steps 2–4 end to end.
x402是一种HTTP支付协议。当服务器返回
HTTP 402 Payment Required
响应时,会包含一个base64编码的JSON负载,描述所需的支付信息。完整流程如下:
  1. 发送请求 → 收到
    HTTP 402
    响应及base64编码的支付负载
  2. 解码负载,从
    accepts[0]
    中提取支付参数
  3. 通过TEE签名 →
    onchainos payment x402-pay
    → 获取
    { signature, authorization }
  4. 组装支付头并重试原请求
本技能负责步骤2-4的全流程。

Quickstart

快速开始

bash
undefined
bash
undefined

Sign 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
undefined
onchainos payment x402-pay
--network eip155:196
--amount 1000000
--pay-to 0xRecipientAddress
--asset 0x4ae46a509f6b1d9056937ba4500cb143933d2dc8
--max-timeout-seconds 300
undefined

Command Index

命令索引

#CommandDescription
1
onchainos payment x402-pay
Sign an x402 payment and return the payment proof
序号命令描述
1
onchainos payment x402-pay
签署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
HTTP 402
, the body is a base64-encoded JSON string. Decode it:
rawBody  = response.body          // base64 string
decoded  = JSON.parse(atob(rawBody))
option   = decoded.accepts[0]
Extract these fields from
option
:
x402 fieldCLI paramNotes
option.network
--network
CAIP-2 format, e.g.
eip155:196
option.amount
or
option.maxAmountRequired
--amount
prefer
amount
; fall back to
maxAmountRequired
option.payTo
--pay-to
option.asset
--asset
token contract address
option.maxTimeoutSeconds
--max-timeout-seconds
optional, default 300
⚠️ MANDATORY: Display payment details and STOP to wait for user confirmation. Do NOT check wallet status, run
onchainos wallet status
, attempt login, or call any other tool until the user explicitly confirms.
Present the following information to the user:
This resource requires x402 payment:
  • Network:
    <chain name>
    (
    <network>
    )
  • Token:
    <token symbol>
    (
    <asset>
    )
  • Amount:
    <human-readable amount>
    (convert from minimal units using token decimals)
  • 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.
如果响应为
HTTP 402
,响应体是一个base64编码的JSON字符串。解码该字符串:
rawBody  = response.body          // base64字符串
decoded  = JSON.parse(atob(rawBody))
option   = decoded.accepts[0]
option
中提取以下字段:
x402字段CLI参数说明
option.network
--network
CAIP-2格式,例如
eip155:196
option.amount
option.maxAmountRequired
--amount
优先使用
amount
;若不存在则使用
maxAmountRequired
option.payTo
--pay-to
option.asset
--asset
代币合约地址
option.maxTimeoutSeconds
--max-timeout-seconds
可选参数,默认值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
    onchainos wallet login
    (AK login, no email) or
    onchainos wallet login <email>
    (OTP login), then proceed to Step 4.
  • User says no → switch to the Local Signing Fallback (see below).
确认需要支付后,检查用户是否有活跃的钱包会话:
bash
onchainos wallet status
  • 已登录 → 进入步骤4(签名)。
  • 未登录 → 询问用户:
"该资源需要x402支付。您需要一个钱包来签署支付信息。是否需要创建一个钱包?(免费,约30秒即可完成。)"
  • 用户同意 → 运行
    onchainos wallet login
    (AK登录,无需邮箱)或
    onchainos wallet login <email>
    (OTP登录),然后进入步骤4。
  • 用户拒绝 → 切换到本地签名回退流程(见下文)。

Step 4: Sign

步骤4:签名

Run
onchainos payment x402-pay
with the extracted parameters. Returns
{ 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
      onchainos wallet login
      or
      onchainos wallet login <email>
      , then retry this step.
    • User wants local signing → switch to the Local Signing Fallback (see below).
    • User wants to cancel → only then cancel the request.
使用提取的参数运行
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 >= 2
    PAYMENT-SIGNATURE
  • x402Version < 2
    (or absent) →
    X-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 >= 2
    PAYMENT-SIGNATURE
  • x402Version < 2
    (或未设置) →
    X-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 completedSuggest
Successful replay1. Check balance impact →
okx-agentic-wallet
2. Make another request to the same resource
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. 查看余额变化 → 使用
okx-agentic-wallet
2. 再次访问同一资源
重试时返回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 200
Data handoff:
  • accepts[0].network
    --network
  • accepts[0].amount
    (or
    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>]
ParamRequiredDefaultDescription
--network
Yes-CAIP-2 network identifier (e.g.,
eip155:196
for X Layer,
eip155:1
for Ethereum)
--amount
Yes-Payment amount in minimal units (e.g.,
1000000
= 1 USDG with 6 decimals)
--pay-to
Yes-Recipient address (from x402
payTo
field)
--asset
Yes-Token contract address (from x402
asset
field)
--from
Noselected accountPayer address; if omitted, uses the currently selected account
--max-timeout-seconds
No
300
Authorization validity window in seconds
Return fields:
FieldTypeDescription
signature
StringEIP-3009 secp256k1 signature (65 bytes, r+s+v, hex) returned by TEE backend
authorization
ObjectStandard x402 EIP-3009
transferWithAuthorization
parameters
authorization.from
StringPayer wallet address
authorization.to
StringRecipient address (=
payTo
)
authorization.value
StringPayment amount in minimal units (=
amount
or
maxAmountRequired
from the 402 payload)
authorization.validAfter
StringAuthorization valid-after timestamp (Unix seconds)
authorization.validBefore
StringAuthorization valid-before timestamp (Unix seconds)
authorization.nonce
StringRandom 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>]
参数是否必填默认值描述
--network
-CAIP-2格式的网络标识符(例如X Layer为
eip155:196
,Ethereum为
eip155:1
--amount
-支付金额,以最小单位计算(例如
1000000
= 1 USDG,小数位数为6)
--pay-to
-收款地址(来自x402的
payTo
字段)
--asset
-代币合约地址(来自x402的
asset
字段)
--from
当前选中的账户付款地址;如果省略,则使用当前选中的账户
--max-timeout-seconds
300
授权的有效时长(秒)
返回字段
字段类型描述
signature
字符串TEE后端返回的EIP-3009 secp256k1签名(65字节,格式为r+s+v,十六进制)
authorization
对象标准x402 EIP-3009
transferWithAuthorization
参数
authorization.from
字符串付款钱包地址
authorization.to
字符串收款地址(等于
payTo
authorization.value
字符串支付金额,以最小单位计算(等于402负载中的
amount
maxAmountRequired
authorization.validAfter
字符串授权生效时间戳(Unix秒级)
authorization.validBefore
字符串授权失效时间戳(Unix秒级)
authorization.nonce
字符串随机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..."  ← base64
Decoded 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": "..." }
undefined

Local 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
    .env
    file, hardware wallet, or MetaMask export)
  • The payer address must hold sufficient ERC-20 balance of the
    asset
    token on the target chain
  • The
    asset
    token contract must support EIP-3009
    transferWithAuthorization
  • 用户拥有本地私钥(例如存储在
    .env
    文件、硬件钱包或从MetaMask导出)
  • 付款地址在目标链上持有足够的
    asset
    代币ERC-20余额
  • asset
    代币合约支持EIP-3009
    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:
network
,
amount
(or
maxAmountRequired
),
payTo
,
asset
,
maxTimeoutSeconds
.
与主流程相同 —— 解码base64编码的响应体,提取
accepts[0]
rawBody  = response.body
decoded  = JSON.parse(atob(rawBody))
option   = decoded.accepts[0]
提取:
network
amount
(或
maxAmountRequired
)、
payTo
asset
maxTimeoutSeconds

Step 2: Construct EIP-3009 Parameters and Sign

步骤2:构造EIP-3009参数并签名

Build the
TransferWithAuthorization
message and sign it with
eth_signTypedData_v4
. Key fields:
FieldValue
from
Payer address
to
option.payTo
value
option.amount
validAfter
"0"
validBefore
now + maxTimeoutSeconds
(Unix seconds)
nonce
Random 32 bytes (hex)
EIP-712 domain: query the token contract's
name()
,
version
(often
"1"
or
"2"
),
chainId
from the CAIP-2 network, and
verifyingContract
=
option.asset
.
Sign 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.name
/
version
vary per token (e.g. USDC uses
"USD Coin"
/
"2"
) — query the contract to confirm.
构建
TransferWithAuthorization
消息,使用
eth_signTypedData_v4
进行签名。关键字段:
字段
from
付款地址
to
option.payTo
value
option.amount
validAfter
"0"
validBefore
当前时间 + maxTimeoutSeconds
(Unix秒级)
nonce
随机32字节十六进制值
EIP-712域:查询代币合约的
name()
version
(通常为
"1"
"2"
)、从CAIP-2网络中获取
chainId
verifyingContract
=
option.asset
使用ethers.js签名
javascript
const wallet = new ethers.Wallet('<PRIVATE_KEY>');
const signature = await wallet.signTypedData(domain, types, message);
完整的类型数据规范请参考EIP-3009
domain.name
/
version
因代币而异(例如USDC使用
"USD Coin"
/
"2"
) —— 请先查询合约确认。

Step 3: Assemble Header and Replay

步骤3:组装支付头并重试

Same as the main flow Step 5 — build
authorization
from the signed fields, determine header name from
x402Version
, assemble
paymentPayload = { ...decoded, payload: { signature, authorization } }
, base64-encode, and replay the original request with the payment header attached.
与主流程步骤5相同 —— 从签名字段构建
authorization
,根据
x402Version
确定头名称,组装
paymentPayload = { ...decoded, payload: { signature, authorization } }
,进行base64编码,然后附加支付头并重试原请求。

Important Notes for Local Signing

本地签名的重要注意事项

  • The private key never leaves the local machine — signing is done entirely offline
  • The
    nonce
    must be a random 32-byte hex value; reusing a nonce will cause the transaction to be rejected
  • validBefore
    is a Unix timestamp in seconds — set it to
    now + maxTimeoutSeconds
    (default 300s / 5 minutes)
  • If the token uses a non-standard EIP-712 domain (e.g., different
    version
    string), the signature will be invalid — always query the contract first
  • The signed authorization only authorizes the exact
    (from, to, value, nonce)
    tuple — it cannot be modified or reused
  • 私钥永远不会离开本地机器 —— 签名完全离线完成
  • nonce
    必须是随机的32字节十六进制值;重复使用nonce会导致交易被拒绝
  • validBefore
    是Unix秒级时间戳 —— 设置为
    当前时间 + maxTimeoutSeconds
    (默认300秒/5分钟)
  • 如果代币使用非标准EIP-712域(例如不同的
    version
    字符串),签名将无效 —— 请务必先查询合约
  • 已签署的授权仅对精确
    (from, to, value, nonce)
    元组有效 —— 无法修改或重复使用

Edge Cases

边缘情况

  • Not logged in: Ask user if they want to create a wallet (
    onchainos wallet login
    or
    onchainos wallet login <email>
    ). If not, guide them through the Local Signing Fallback above
  • Unsupported network: Only EVM chains with CAIP-2
    eip155:<chainId>
    format are supported
  • 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:
    --amount
    must be in minimal units — remind user to convert (e.g., 1 USDG =
    1000000
    for 6 decimals)
  • 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格式为
    eip155:<chainId>
    的EVM链
  • 目标链无钱包:已登录的账户必须在目标链上拥有地址;如果没有,告知用户
  • 金额单位错误
    --amount
    必须以最小单位计算 —— 提醒用户进行转换(例如1 USDG =
    1000000
    ,小数位数为6)
  • 授权过期:如果服务器拒绝支付并提示过期,则重新执行步骤4获取新签名
  • 网络错误:重试一次,然后提示用户稍后再试

Amount Display Rules

金额显示规则

  • --amount
    is always in minimal units (e.g.,
    1000000
    for 1 USDG)
  • When displaying to the user, convert to UI units: divide by
    10^decimal
  • Show token symbol alongside (e.g.,
    1.00 USDG
    )
  • --amount
    始终以最小单位计算(例如1 USDG对应
    1000000
  • 向用户显示时,转换为可读单位:除以
    10^decimal
  • 同时显示代币符号(例如
    1.00 USDG

Global Notes

全局说明

  • Primary path (
    onchainos payment x402-pay
    ): requires an authenticated JWT session; signing is performed inside a TEE — the private key never leaves the secure enclave
  • 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
  • --network
    must be CAIP-2 format:
    eip155:<chainId>
    (e.g.,
    eip155:1
    ,
    eip155:8453
    ,
    eip155:196
    )
  • The returned
    authorization
    object must be included alongside
    signature
    when building the payment header
  • 主路径
    onchainos payment x402-pay
    ):需要已认证的JWT会话;签名在TEE内部执行 —— 私钥永远不会离开安全飞地
  • 回退路径(本地签名):需要用户自身的私钥;签名完全在本地机器上完成 —— 无需JWT或TEE
  • 本技能仅负责签名 —— 不直接广播交易或扣除余额;当收款方在链上兑现授权时,支付才会完成
  • --network
    必须为CAIP-2格式:
    eip155:<chainId>
    (例如
    eip155:1
    eip155:8453
    eip155:196
  • 返回的
    authorization
    对象必须与
    signature
    一起包含在支付头中