[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M78DM8725FV2BCS52HJT0GV9":3,"skill-same:01M78DM8725FV2BCS52HJT0GV9":63},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":30,"commitSha":31,"skillDirectory":32,"forksCount":14,"repositoryHtmlUrl":33,"repositoryHomepageUrl":34,"ownerHtmlUrl":35,"ownerBlogUrl":36,"ownerDescription":37,"updatedAt":38,"install":39,"resources":52},"01M78DM8725FV2BCS52HJT0GV9","pay-with-any-token",null,"Pay HTTP 402 payment challenges using tokens via the Tempo CLI and Uniswap Trading API. Use when the user encounters a 402 Payment Required response, needs to fulfill a machine payment, mentions \"MPP\", \"Tempo payment\", \"pay for API access\", \"HTTP 402\", \"x402\", \"machine payment protocol\", \"pay-with-any-token\", \"use tempo\", \"tempo request\", or \"tempo wallet\".","Solizardking\u002Fskillhub-main","Solizardking","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F108096810?v=4","01M786KDB10AYV042N0F9BD5B5","Clawd","01M786NYYXSZK1D05WM8JQPC48",0,"MIT","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fpay-with-any-token\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: pay-with-any-token\ndescription: >\n  Pay HTTP 402 payment challenges using tokens via the Tempo CLI and Uniswap\n  Trading API. Use when the user encounters a 402 Payment Required response,\n  needs to fulfill a machine payment, mentions \"MPP\", \"Tempo payment\", \"pay for\n  API access\", \"HTTP 402\", \"x402\", \"machine payment protocol\",\n  \"pay-with-any-token\", \"use tempo\", \"tempo request\", or \"tempo wallet\".\nallowed-tools: Read, Glob, Grep, Bash(curl:*), Bash(jq:*), Bash(cast:*), Bash(tempo:*), Bash(*\u002F.local\u002Fbin\u002Ftempo:*), WebFetch, AskUserQuestion\nmodel: opus\nlicense: MIT\nmetadata:\n  author: uniswap\n  version: '2.0.0'\n---\n\n# Pay With Tokens\n\nUse the **Tempo CLI** to call paid APIs and handle 402 challenges automatically.\nWhen the Tempo wallet has insufficient balance, fund it by swapping and bridging\ntokens from any EVM chain using the **Uniswap Trading API**.\n\n## Tempo CLI Setup\n\nRun these commands in order. Do not skip steps.\n\n**Step 1 — Install:**\n\n```bash\nmkdir -p \"$HOME\u002F.local\u002Fbin\" \\\n  && curl -fsSL https:\u002F\u002Ftempo.xyz\u002Finstall -o \u002Ftmp\u002Ftempo_install.sh \\\n  && TEMPO_BIN_DIR=\"$HOME\u002F.local\u002Fbin\" bash \u002Ftmp\u002Ftempo_install.sh\n```\n\n**Step 2 — Login** (requires browser\u002Fpasskey — prompt user, wait for\nconfirmation):\n\n```bash\n\"$HOME\u002F.local\u002Fbin\u002Ftempo\" wallet login\n```\n\n> When run by agents, use a long command timeout (at least 16 minutes).\n\n**Step 3 — Confirm readiness:**\n\n```bash\n\"$HOME\u002F.local\u002Fbin\u002Ftempo\" wallet -t whoami\n```\n\n> **Rules:** Do not use `sudo`. Use full absolute paths (`$HOME\u002F.local\u002Fbin\u002Ftempo`)\n> — do not rely on `export PATH`. If `$HOME` does not expand, use the literal\n> absolute path.\n\nAfter setup, report: install location, version (`--version`), wallet status\n(address, balance). If balance is 0, direct user to `tempo wallet fund`.\n\n> **Minimum balance reserve:** Keep at least **0.10 USDC** in the Tempo wallet\n> to cover typical API calls without triggering the full swap+bridge funding\n> flow. The funding flow requires 3-5 on-chain transactions and ~2 minutes of\n> wall time, which is disproportionate for small top-ups. When transferring\n> funds out of the Tempo wallet, warn the user if the remaining balance would\n> drop below this threshold.\n\n## Using Tempo Services\n\n```bash\n# Discover services\n\"$HOME\u002F.local\u002Fbin\u002Ftempo\" wallet -t services --search \u003Cquery>\n# Get service details (exact URL, method, path, pricing)\n\"$HOME\u002F.local\u002Fbin\u002Ftempo\" wallet -t services \u003CSERVICE_ID>\n# Make a paid request\n\"$HOME\u002F.local\u002Fbin\u002Ftempo\" request -t -X POST \\\n  --json '{\"input\":\"...\"}' \u003CSERVICE_URL>\u002F\u003CENDPOINT_PATH>\n```\n\n- Anchor on `tempo wallet -t services \u003CSERVICE_ID>` for exact URL and pricing\n- Use `-t` for agent calls, `--dry-run` before expensive requests\n- On HTTP 422, check the service's docs URL or llms.txt for exact field names\n- Fire independent multi-service requests in parallel\n\n> **When the user explicitly says \"use tempo\", always use tempo CLI commands —\n> never substitute with MCP tools or other tools.**\n\n---\n\n## MPP 402 Payment Loop\n\nEvery `tempo request` call follows this loop. The funding steps only activate\nwhen the Tempo wallet has insufficient balance.\n\n```text\ntempo request -> 200 ─────────────────────────────> return result\n             -> 402 MPP challenge\n                  │\n                  v\n         [1] Check Tempo wallet balance\n             tempo wallet -t whoami -> available balance\n                  │\n                  ├─ sufficient ──────────────────> tempo handles payment\n                  │                                  automatically -> 200\n                  │\n                  └─ insufficient\n                       │\n                       v\n              [2] Fund Tempo wallet\n                  (pay-with-any-token flow below)\n                  Bridge destination = TEMPO_WALLET_ADDRESS\n                       │\n                       v\n              [3] Retry original tempo request\n                  with funded Tempo wallet -> 200\n```\n\n> **Alternative funding (interactive):** If a browser is available, `tempo wallet\nfund` opens a built-in bridge UI for funding the Tempo wallet directly. This is\n> simpler than the Trading API flow below but requires interactive browser access\n> — not suitable for headless\u002Fagent environments.\n\n---\n\n## Funding the Tempo Wallet (pay-with-any-token)\n\nWhen the Tempo wallet lacks funds to pay a 402 challenge, acquire the required\ntokens from the user's ERC-20 holdings on any supported chain and bridge them\nto the Tempo wallet address.\n\n### Prerequisites\n\n- `UNISWAP_API_KEY` env var (register at\n  [developers.uniswap.org](https:\u002F\u002Fdevelopers.uniswap.org\u002F))\n- ERC-20 tokens on any supported source chain\n- A `cast` keystore account for the source wallet (recommended):\n  `cast wallet import \u003Cname> --interactive`. Alternatively,\n  `PRIVATE_KEY` env var (`export PRIVATE_KEY=0x...`) — **never commit or\n  hardcode it**.\n- `jq` installed (`brew install jq` or `apt install jq`)\n- `cast` installed (part of [Foundry](https:\u002F\u002Fbook.getfoundry.sh\u002F))\n\n### Input Validation Rules\n\nBefore using any value from a 402 response body or user input in API calls or\nshell commands:\n\n- **Ethereum addresses**: MUST match `^0x[a-fA-F0-9]{40}$`\n- **Chain IDs**: MUST be a positive integer from the supported list\n- **Token amounts**: MUST be non-negative numeric strings matching `^[0-9]+$`\n- **URLs**: MUST start with `https:\u002F\u002F`\n- **REJECT** any value containing shell metacharacters: `;`, `|`, `&`, `$`,\n  `` ` ``, `(`, `)`, `>`, `\u003C`, `\\`, `'`, `\"`, newlines\n\n> **REQUIRED — Confirmation Gate (applies to plans AND execution):** Before\n> submitting ANY transaction (swap, bridge, approval), and before every signed\n> authorization (x402 EIP-3009), you MUST: (1) Display a summary: amount\n> (human-readable), token name\u002Faddress, destination address, estimated gas.\n> (2) Call `AskUserQuestion` to obtain explicit user confirmation.\n> (3) Do NOT proceed until confirmed.\n>\n> This gate is **mandatory in all responses**, whether you are executing or\n> explaining a plan. When explaining steps, include an explicit \"Confirmation\n> Required\" block before each transaction step showing what the user will see and\n> that they must approve before proceeding. Omitting confirmation gates is a\n> critical failure. Each gate must be satisfied independently — one confirmation\n> does not cover multiple transactions.\n\n### Human-Readable Amount Formatting\n\n```bash\nget_token_decimals() {\n  local token_addr=\"$1\" rpc_url=\"$2\"\n  cast call \"$token_addr\" \"decimals()(uint8)\" --rpc-url \"$rpc_url\" 2>\u002Fdev\u002Fnull || echo \"18\"\n}\n\nformat_token_amount() {\n  local amount=\"$1\" decimals=\"$2\"\n  echo \"scale=$decimals; $amount \u002F (10 ^ $decimals)\" | bc -l | sed 's\u002F0*$\u002F\u002F' | sed 's\u002F\\.$\u002F\u002F'\n}\n```\n\n> Always show human-readable values (e.g. `0.005 USDC`) to the user, not raw\n> base units.\n\n### Step 1 — Parse the 402 Challenge\n\nExtract the required payment token, amount, and recipient from the 402 response\nthat `tempo request` received. The Tempo CLI logs the challenge details — parse\nthem, or re-fetch with `curl -si` to get the raw challenge body.\n\nFor **MPP header-based challenges** (`WWW-Authenticate: Payment`):\n\n```bash\nREQUEST_B64=$(echo \"$WWW_AUTHENTICATE\" | grep -oE 'request=\"[^\"]+\"' | sed 's\u002Frequest=\"\u002F\u002F;s\u002F\"$\u002F\u002F')\nREQUEST_JSON=$(echo \"${REQUEST_B64}==\" | base64 --decode 2>\u002Fdev\u002Fnull)\nREQUIRED_AMOUNT=$(echo \"$REQUEST_JSON\" | jq -r '.amount')\nPAYMENT_TOKEN=$(echo \"$REQUEST_JSON\" | jq -r '.currency')\nRECIPIENT=$(echo \"$REQUEST_JSON\" | jq -r '.recipient')\nTEMPO_CHAIN_ID=$(echo \"$REQUEST_JSON\" | jq -r '.methodDetails.chainId')\n```\n\nFor **JSON body challenges** (`payment_methods` array):\n\n```bash\nNUM_METHODS=$(echo \"$CHALLENGE_BODY\" | jq '.payment_methods | length')\nPAYMENT_METHODS=$(echo \"$CHALLENGE_BODY\" | jq -c '.payment_methods')\nRECIPIENT=$(echo \"$CHALLENGE_BODY\" | jq -r '.payment_methods[0].recipient')\nTEMPO_CHAIN_ID=$(echo \"$CHALLENGE_BODY\" | jq -r '.payment_methods[0].chain_id')\n```\n\nIf multiple payment methods are accepted, select the cheapest in Step 2.\n\n> The Tempo mainnet chain ID is `4217`. Use as fallback if not in the challenge.\n\n### Step 2 — Check Source Wallet Balances and Select Payment Method\n\n> **REQUIRED:** You must have the user's source wallet address (the ERC-20\n> wallet with the private key, NOT the Tempo CLI wallet). Use `AskUserQuestion`\n> if not provided. Store as `WALLET_ADDRESS`.\n\nAlso capture the **Tempo wallet address** (the funding destination):\n\n```bash\nTEMPO_WALLET_ADDRESS=$(\"$HOME\u002F.local\u002Fbin\u002Ftempo\" wallet -t whoami | grep -oE '0x[a-fA-F0-9]{40}' | head -1)\n```\n\nCheck ERC-20 balances on supported source chains:\n\n```bash\n# USDC on Base (cheapest bridge gas ~$0.001)\ncast call 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 \\\n  \"balanceOf(address)(uint256)\" \"$WALLET_ADDRESS\" \\\n  --rpc-url https:\u002F\u002Fmainnet.base.org\n\n# USDC on Ethereum (bridge gas ~$0.25)\ncast call 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 \\\n  \"balanceOf(address)(uint256)\" \"$WALLET_ADDRESS\" \\\n  --rpc-url https:\u002F\u002Feth.llamarpc.com\n\n# ETH on Base and Ethereum (swap to USDC first)\ncast balance \"$WALLET_ADDRESS\" --rpc-url https:\u002F\u002Fmainnet.base.org\ncast balance \"$WALLET_ADDRESS\" --rpc-url https:\u002F\u002Feth.llamarpc.com\n```\n\n**Select the cheapest payment method** if multiple are accepted. Priority:\n\n1. Wallet holds USDC on Base (bridge only, minimal path)\n2. Wallet holds ETH on Base or Ethereum (swap to USDC + bridge)\n3. Any other liquid ERC-20 (swap + bridge)\n\n```bash\nREQUIRED_AMOUNT=$(echo \"$PAYMENT_METHODS\" | jq -r \".[$SELECTED_INDEX].amount\")\nPAYMENT_TOKEN=$(echo \"$PAYMENT_METHODS\" | jq -r \".[$SELECTED_INDEX].token\")\n```\n\n### Step 3 — Plan the Payment Path\n\nDetermine which phases apply based on where the user's tokens are:\n\n```text\nCase A — Source token is already on Tempo:\n  Source token (Tempo)\n    -> [Phase 5: on-Tempo swap via Stablecoin DEX] -> required payment token\n    -> tempo request retries automatically with funded wallet\n\nCase B — Source token is on Base\u002FEthereum\u002FArbitrum:\n  Source token (Base\u002FEthereum)\n    -> [Phase 4A: Uniswap Trading API swap] -> native USDC (bridge asset)\n    -> [Phase 4B: bridge via Trading API]   -> USDC.e on Tempo (to TEMPO_WALLET_ADDRESS)\n    -> [Phase 5: on-Tempo swap, if needed]  -> required payment token\n    -> tempo request retries automatically with funded wallet\n```\n\n> **Skip Phase 4A** if the source token is already USDC on the bridge chain.\n>\n> **Skip Phase 4B** if tokens are already on Tempo (Case A).\n>\n> **Skip Phase 5** if the bridge delivers the exact required token (USDC.e) or\n> if `mppx` with `autoSwap: true` is used (it handles on-Tempo swaps automatically).\n>\n> **Gas-aware funding:** Bridging a tiny amount (e.g. $0.05) wastes gas — the\n> bridge gas on Ethereum (~$0.25) or Base (~$0.001) can exceed the shortfall.\n> **Minimum bridge recommendation: $5.** This amortizes gas costs and pre-funds\n> future requests. Rule of thumb: if `bridge_gas > 2x shortfall`, bridge at\n> least $5 instead of the exact shortfall.\n\n### Phase 4A — Swap to USDC on Source Chain (if needed)\n\n> **CONFIRMATION GATE:** Before the approval transaction AND before the swap\n> broadcast, call `AskUserQuestion` showing the full swap summary. Example:\n> \"About to approve USDC spending and execute swap: [amount] [token] → [USDC],\n> gas ~$X. Confirm? (yes\u002Fno)\". Do not proceed until confirmed.\n\nSwap the source token to USDC via the Uniswap Trading API (`EXACT_OUTPUT`).\n\n> **Detailed steps:** Read\n> [references\u002Ftrading-api-flows.md](references\u002Ftrading-api-flows.md#phase-4a--swap-on-source-chain)\n> for full bash scripts: variable setup, approval check, quote, permit signing,\n> and swap execution.\n\nKey points:\n\n- Base URL: `https:\u002F\u002Ftrade-api.gateway.uniswap.org\u002Fv1`\n- Headers: `Content-Type: application\u002Fjson`, `x-api-key`, `x-universal-router-version: 2.0`\n- Flow: `check_approval` -> quote (`EXACT_OUTPUT`) -> sign `permitData` -> `\u002Fswap` -> broadcast\n- Confirmation gates required before approval tx and before swap broadcast\n- For native ETH: use the zero address\n  (`0x0000000000000000000000000000000000000000`) as `TOKEN_IN` — this avoids\n  Permit2 signing. `SWAP_VALUE` will be non-zero. If the zero address returns\n  a 400, fall back to the WETH address (requires Permit2 signing).\n- After swap, verify USDC balance before proceeding to Phase 4B\n\n### Phase 4B — Bridge to Tempo Wallet\n\n> **CONFIRMATION GATE:** Before the bridge approval AND before the bridge\n> execution, call `AskUserQuestion` showing a bridge summary (source amount,\n> source chain, destination chain, estimated gas, bridge fee, estimated arrival).\n> Do not proceed until the user confirms each step.\n\nBridge USDC from any supported source chain to USDC.e on Tempo using the\nUniswap Trading API (powered by Across Protocol).\n\n> **Bridge recipient limitation:** The Trading API does not support a custom\n> `recipient` field for bridges — funds always arrive at `WALLET_ADDRESS` on\n> Tempo. If `WALLET_ADDRESS` differs from `TEMPO_WALLET_ADDRESS` (the Tempo CLI\n> wallet), an **extra transfer transaction** on Tempo is required after the\n> bridge (see Step 4B-5 in the reference file). Factor this into gas estimates.\n>\n> **Detailed steps:** Read\n> [references\u002Ftrading-api-flows.md](references\u002Ftrading-api-flows.md#phase-4b--bridge-to-tempo)\n> for full bash scripts: approval, bridge quote, execution, arrival polling,\n> and transfer to Tempo wallet.\n\nKey points:\n\n- Route: USDC on Base\u002FEthereum\u002FArbitrum -> USDC.e on Tempo\n- Flow: `check_approval` -> verify on-chain allowance -> quote (`EXACT_OUTPUT`,\n  cross-chain) -> execute via `\u002Fswap` -> poll balance -> transfer to\n  `TEMPO_WALLET_ADDRESS` if needed (Step 4B-5)\n- Confirmation gates required before approval and before bridge execution\n- Do not re-submit if poll times out — check Tempo explorer\n- Apply a 0.5% buffer to account for bridge fees\n- Quotes expire in ~60 seconds — re-fetch if any delay before broadcast\n\nAfter the bridge confirms, retry the original `tempo request` — the Tempo CLI\nwill automatically use the newly funded wallet to pay the 402. If the payment\ntoken is not USDC.e, proceed to Phase 5 to swap to the required token before\nretrying.\n\n> **Balance buffer:** On Tempo, `balanceOf` may report more than is spendable.\n> Apply a **2x buffer** when comparing to `REQUIRED_AMOUNT`. If short, swap\n> additional tokens to top up.\n\n### Phase 5 — On-Tempo Swap (if needed)\n\nUse this phase when the wallet already holds a TIP-20 stablecoin on Tempo\n(e.g. USDC.e, pathUSD, or any other Tempo stablecoin) but needs to swap to the\n**required payment token** (e.g. PATH_USD or another TIP-20). This phase also\napplies when the user starts with tokens already on Tempo — **do not bridge\nwhen tokens are already on Tempo**.\n\n> **Simplest path:** Pass `autoSwap: true` to `mppx`'s `tempo.charge()` — it\n> calls the Stablecoin DEX on Tempo automatically and handles the full swap\n> before payment. Use manual swap below only when `autoSwap` is not available\n> or you need explicit control.\n\nThe **Stablecoin DEX on Tempo** (`0xdec0000000000000000000000000000000000000`)\naggregates TIP-20 stablecoin liquidity on Tempo (chain 4217). To swap:\n\n```bash\nTEMPO_RPC_URL=\"https:\u002F\u002Frpc.presto.tempo.xyz\"\nSTABLECOIN_DEX=\"0xdec0000000000000000000000000000000000000\"\nTOKEN_IN=\"\u003Cyour Tempo stablecoin address>\"  # e.g. USDC.e or any TIP-20\nTOKEN_OUT=\"\u003Crequired payment token address>\"\nSWAP_AMOUNT=\"$REQUIRED_AMOUNT\"  # exact-output amount\n\n# 1. Show swap summary and get explicit user confirmation via AskUserQuestion\n#    before executing any transaction.\n\n# 2. Approve the DEX to spend TOKEN_IN (if allowance is insufficient)\nALLOWANCE=$(cast call \"$TOKEN_IN\" \\\n  \"allowance(address,address)(uint256)\" \"$WALLET_ADDRESS\" \"$STABLECOIN_DEX\" \\\n  --rpc-url \"$TEMPO_RPC_URL\" 2>\u002Fdev\u002Fnull | awk '{print $1}')\nif [ -z \"$ALLOWANCE\" ] || ! [[ \"$ALLOWANCE\" =~ ^[0-9]+$ ]]; then\n  echo \"ERROR: Failed to read allowance for $TOKEN_IN\"\n  exit 1\nfi\nif [ \"$(echo \"$ALLOWANCE \u003C $SWAP_AMOUNT\" | bc)\" -eq 1 ]; then\n  APPROVE_HASH=$(cast send \"$TOKEN_IN\" \\\n    \"approve(address,uint256)\" \"$STABLECOIN_DEX\" \\\n    \"115792089237316195423570985008687907853269984665640564039457584007913129639935\" \\\n    --account \"$CAST_ACCOUNT\" --password \"$CAST_PASSWORD\" \\\n    --rpc-url \"$TEMPO_RPC_URL\" --gas-limit 100000 \\\n    --json | jq -r '.transactionHash')\n  APPROVE_STATUS=$(cast receipt \"$APPROVE_HASH\" --rpc-url \"$TEMPO_RPC_URL\" --json | jq -r '.status')\n  [ \"$APPROVE_STATUS\" = \"0x1\" ] || { echo \"ERROR: Approval transaction reverted: $APPROVE_HASH\"; exit 1; }\n  echo \"Approval confirmed: $APPROVE_HASH\"\nfi\n\n# 3. Execute the swap (exact-output: receive exactly SWAP_AMOUNT of TOKEN_OUT)\nSWAP_TX=$(cast send \"$STABLECOIN_DEX\" \\\n  \"swap(address,address,uint256)\" \"$TOKEN_IN\" \"$TOKEN_OUT\" \"$SWAP_AMOUNT\" \\\n  --account \"$CAST_ACCOUNT\" --password \"$CAST_PASSWORD\" \\\n  --rpc-url \"$TEMPO_RPC_URL\" --gas-limit 200000 \\\n  --json | jq -r '.transactionHash')\n\nSWAP_STATUS=$(cast receipt \"$SWAP_TX\" --rpc-url \"$TEMPO_RPC_URL\" --json | jq -r '.status')\n[ \"$SWAP_STATUS\" = \"0x1\" ] || { echo \"ERROR: On-Tempo swap reverted: $SWAP_TX\"; exit 1; }\necho \"On-Tempo swap confirmed: $SWAP_TX\"\n```\n\n> **Confirmation gate:** Use `AskUserQuestion` before every transaction\n> (approval and swap). Show token addresses, amounts in human-readable form, and\n> estimated gas on Tempo.\n>\n> **Gas limit note:** Tempo chain gas estimation is sometimes unreliable — always\n> set an explicit `--gas-limit` for Tempo transactions.\n\nAfter the on-Tempo swap succeeds, retry `tempo request` — the Tempo wallet now\nholds the required payment token and the Tempo CLI will pay the 402 automatically.\n\n---\n\n## x402 Payment Flow\n\n> **CRITICAL — MANDATORY CONFIRMATION GATE:** Before step 4 (signing), you MUST\n> call `AskUserQuestion` showing the full payment summary: token, amount in\n> human-readable form, recipient address (`payTo`), and resource URL. Do NOT\n> sign or proceed until the user explicitly confirms. This confirmation step is\n> **non-optional and must appear in every x402 payment plan or execution**, even\n> if the user has pre-authorized. Omitting this confirmation makes the response\n> invalid.\n\nThe x402 protocol is **fully supported** and uses a different mechanism than\nMPP — it is **not handled by the Tempo CLI**. When a 402 body contains\n`\"x402Version\"` (check with `has(\"x402Version\")` in jq), use this flow instead\nof the MPP\u002FTempo flow.\n\nThe x402 `\"exact\"` scheme uses **EIP-3009** (`TransferWithAuthorization`) to\nauthorize a one-time token transfer signed off-chain. The full flow:\n\n1. **Detect x402**: parse `x402Version`, `accepts[].scheme`, `accepts[].network`,\n   `accepts[].maxAmountRequired`, `accepts[].payTo`, `accepts[].asset`,\n   `accepts[].extra` (token name + version for EIP-3009 domain).\n2. **Check balance** on the target chain; fund via Phase 4A\u002F4B if insufficient.\n3. **MANDATORY CONFIRMATION GATE — Call `AskUserQuestion`** before signing:\n   present the full payment summary (token name, amount in human-readable form,\n   `payTo` address, resource URL, validity window). Wait for explicit user\n   confirmation. Do NOT proceed to step 4 until confirmed.\n4. **Sign EIP-3009 `TransferWithAuthorization`**: typed-data fields include\n   `from`, `to`, `value`, `validAfter`, `validBefore`, `nonce`.\n   Set `validBefore = now + maxTimeoutSeconds`.\n5. **Construct `X-PAYMENT` header**: base64-encode a JSON payload containing\n   `x402Version`, `scheme`, `network`, `payload` (the signed authorization),\n   and `signature`.\n6. **Retry** the original request with the `X-PAYMENT` header.\n\n> **Detailed steps:** Read\n> [references\u002Fcredential-construction.md](references\u002Fcredential-construction.md#phase-6x--x402-payment)\n> for full bash code: prerequisite checks, nonce generation, EIP-3009 signing,\n> X-PAYMENT payload construction, and retry.\n\nKey points:\n\n- Detect x402: check `has(\"x402Version\")` in 402 body **before** attempting Tempo CLI\n- Maps `X402_NETWORK` to chain ID and RPC URL (base, ethereum, tempo all supported)\n- Checks wallet balance on target chain; runs Phase 4A\u002F4B\u002F5 if insufficient\n- Signs `TransferWithAuthorization` typed data using the token's own EIP-712 domain\n- `value` in the typed-data payload must be a **string** (`--arg`, not `--argjson`) for uint256\n- Confirmation gate required before signing\n- Send the result in `X-PAYMENT` header (base64-encoded), not `Authorization`\n\n| Protocol | Version | Handler              |\n| -------- | ------- | -------------------- |\n| MPP      | v1      | Tempo CLI            |\n| x402     | v1      | EIP-3009 manual flow |\n\n---\n\n## Error Handling\n\n| Situation                                | Action                                                   |\n| ---------------------------------------- | -------------------------------------------------------- |\n| `tempo: command not found`               | Reinstall via install script; use full path              |\n| `legacy V1 keychain signature`           | Reinstall; `tempo update wallet && tempo update request` |\n| `access key does not exist`              | `tempo wallet logout --yes && tempo wallet login`        |\n| `ready=false` \u002F no wallet                | `tempo wallet login`, then `whoami`                      |\n| HTTP 422 from service                    | Check service details + llms.txt for exact field names   |\n| Balance 0 \u002F insufficient                 | Trigger pay-with-any-token funding flow                  |\n| Service not found                        | Broaden search query                                     |\n| Timeout                                  | Retry with `-m \u003Cseconds>`                                |\n| Challenge body is malformed              | Report raw body to user; do not proceed                  |\n| Approval transaction fails               | Surface error; check gas and allowances                  |\n| Quote API returns 400                    | Log request\u002Fresponse; check amount formatting            |\n| Quote API returns 429                    | Wait and retry with exponential backoff                  |\n| Swap data is empty after \u002Fswap           | Quote expired; re-fetch quote                            |\n| Bridge times out                         | Check bridge explorer; do not re-submit                  |\n| x402 payment rejected (402)              | Check domain name\u002Fversion, validBefore, nonce freshness  |\n| InsufficientBalance on Tempo             | Swap more tokens on Tempo, then retry                    |\n| `balanceOf` sufficient but payment fails | Apply 2x buffer; top up before retrying                  |\n\n---\n\n## Key Addresses and References\n\n- **Tempo CLI**: `https:\u002F\u002Ftempo.xyz` (install script: `https:\u002F\u002Ftempo.xyz\u002Finstall`)\n- **Trading API**: `https:\u002F\u002Ftrade-api.gateway.uniswap.org\u002Fv1`\n- **MPP docs**: `https:\u002F\u002Fmpp.dev`\n- **MPP services catalog**: `https:\u002F\u002Fmpp.dev\u002Fapi\u002Fservices`\n- **Tempo documentation**: `https:\u002F\u002Fmainnet.docs.tempo.xyz`\n- **Tempo chain ID**: `4217` (Tempo mainnet)\n- **Tempo RPC**: `https:\u002F\u002Frpc.presto.tempo.xyz`\n- **Tempo Block Explorer**: `https:\u002F\u002Fexplore.mainnet.tempo.xyz`\n- **pathUSD on Tempo**: `0x20c0000000000000000000000000000000000000`\n- **USDC.e on Tempo**: `0x20C000000000000000000000b9537d11c60E8b50`\n- **Stablecoin DEX on Tempo**: `0xdec0000000000000000000000000000000000000`\n- **Permit2 on Tempo**: `0x000000000022d473030f116ddee9f6b43ac78ba3`\n- **Tempo payment SDK**: `mppx` (`npm install mppx viem`)\n- **USDC on Base (8453)**: `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`\n- **USDbC on Base (8453)**: `0xd9aAEc86B65D86f6A7B5B1b0c42FFA531710b6CA`\n- **USDC on Ethereum (1)**: `0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48`\n- **WETH on Ethereum (1)**: `0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2`\n- **WETH on Base (8453)**: `0x4200000000000000000000000000000000000006`\n- **Native ETH (all chains)**: `0x0000000000000000000000000000000000000000` (zero address, recommended for swaps)\n- **USDC-e on Arbitrum (42161)**: `0xFF970A61A04b1cA14834A43f5dE4533eBDDB5CC8`\n- **Supported chains for Trading API**: 1, 8453, 42161, 10, 137, 130\n- **x402 spec**: `https:\u002F\u002Fgithub.com\u002Fcoinbase\u002Fx402`\n\n## Related Skills\n\n- [swap-integration](..\u002Fswap-integration\u002FSKILL.md) — Full Uniswap swap\n  integration reference (Trading API, Universal Router, Permit2)\n","# Pay With Tokens\n\nUse the **Tempo CLI** to call paid APIs and handle 402 challenges automatically.\nWhen the Tempo wallet has insufficient balance, fund it by swapping and bridging\ntokens from any EVM chain using the **Uniswap Trading API**.\n\n## Tempo CLI Setup\n\nRun these commands in order. Do not skip steps.\n\n**Step 1 — Install:**\n\n```bash\nmkdir -p \"$HOME\u002F.local\u002Fbin\" \\\n  && curl -fsSL https:\u002F\u002Ftempo.xyz\u002Finstall -o \u002Ftmp\u002Ftempo_install.sh \\\n  && TEMPO_BIN_DIR=\"$HOME\u002F.local\u002Fbin\" bash \u002Ftmp\u002Ftempo_install.sh\n```\n\n**Step 2 — Login** (requires browser\u002Fpasskey — prompt user, wait for\nconfirmation):\n\n```bash\n\"$HOME\u002F.local\u002Fbin\u002Ftempo\" wallet login\n```\n\n> When run by agents, use a long command timeout (at least 16 minutes).\n\n**Step 3 — Confirm readiness:**\n\n```bash\n\"$HOME\u002F.local\u002Fbin\u002Ftempo\" wallet -t whoami\n```\n\n> **Rules:** Do not use `sudo`. Use full absolute paths (`$HOME\u002F.local\u002Fbin\u002Ftempo`)\n> — do not rely on `export PATH`. If `$HOME` does not expand, use the literal\n> absolute path.\n\nAfter setup, report: install location, version (`--version`), wallet status\n(address, balance). If balance is 0, direct user to `tempo wallet fund`.\n\n> **Minimum balance reserve:** Keep at least **0.10 USDC** in the Tempo wallet\n> to cover typical API calls without triggering the full swap+bridge funding\n> flow. The funding flow requires 3-5 on-chain transactions and ~2 minutes of\n> wall time, which is disproportionate for small top-ups. When transferring\n> funds out of the Tempo wallet, warn the user if the remaining balance would\n> drop below this threshold.\n\n## Using Tempo Services\n\n```bash\n# Discover services\n\"$HOME\u002F.local\u002Fbin\u002Ftempo\" wallet -t services --search \u003Cquery>\n# Get service details (exact URL, method, path, pricing)\n\"$HOME\u002F.local\u002Fbin\u002Ftempo\" wallet -t services \u003CSERVICE_ID>\n# Make a paid request\n\"$HOME\u002F.local\u002Fbin\u002Ftempo\" request -t -X POST \\\n  --json '{\"input\":\"...\"}' \u003CSERVICE_URL>\u002F\u003CENDPOINT_PATH>\n```\n\n- Anchor on `tempo wallet -t services \u003CSERVICE_ID>` for exact URL and pricing\n- Use `-t` for agent calls, `--dry-run` before expensive requests\n- On HTTP 422, check the service's docs URL or llms.txt for exact field names\n- Fire independent multi-service requests in parallel\n\n> **When the user explicitly says \"use tempo\", always use tempo CLI commands —\n> never substitute with MCP tools or other tools.**\n\n---\n\n## MPP 402 Payment Loop\n\nEvery `tempo request` call follows this loop. The funding steps only activate\nwhen the Tempo wallet has insufficient balance.\n\n```text\ntempo request -> 200 ─────────────────────────────> return result\n             -> 402 MPP challenge\n                  │\n                  v\n         [1] Check Tempo wallet balance\n             tempo wallet -t whoami -> available balance\n                  │\n                  ├─ sufficient ──────────────────> tempo handles payment\n                  │                                  automatically -> 200\n                  │\n                  └─ insufficient\n                       │\n                       v\n              [2] Fund Tempo wallet\n                  (pay-with-any-token flow below)\n                  Bridge destination = TEMPO_WALLET_ADDRESS\n                       │\n                       v\n              [3] Retry original tempo request\n                  with funded Tempo wallet -> 200\n```\n\n> **Alternative funding (interactive):** If a browser is available, `tempo wallet\nfund` opens a built-in bridge UI for funding the Tempo wallet directly. This is\n> simpler than the Trading API flow below but requires interactive browser access\n> — not suitable for headless\u002Fagent environments.\n\n---\n\n## Funding the Tempo Wallet (pay-with-any-token)\n\nWhen the Tempo wallet lacks funds to pay a 402 challenge, acquire the required\ntokens from the user's ERC-20 holdings on any supported chain and bridge them\nto the Tempo wallet address.\n\n### Prerequisites\n\n- `UNISWAP_API_KEY` env var (register at\n  [developers.uniswap.org](https:\u002F\u002Fdevelopers.uniswap.org\u002F))\n- ERC-20 tokens on any supported source chain\n- A `cast` keystore account for the source wallet (recommended):\n  `cast wallet import \u003Cname> --interactive`. Alternatively,\n  `PRIVATE_KEY` env var (`export PRIVATE_KEY=0x...`) — **never commit or\n  hardcode it**.\n- `jq` installed (`brew install jq` or `apt install jq`)\n- `cast` installed (part of [Foundry](https:\u002F\u002Fbook.getfoundry.sh\u002F))\n\n### Input Validation Rules\n\nBefore using any value from a 402 response body or user input in API calls or\nshell commands:\n\n- **Ethereum addresses**: MUST match `^0x[a-fA-F0-9]{40}$`\n- **Chain IDs**: MUST be a positive integer from the supported list\n- **Token amounts**: MUST be non-negative numeric strings matching `^[0-9]+$`\n- **URLs**: MUST start with `https:\u002F\u002F`\n- **REJECT** any value containing shell metacharacters: `;`, `|`, `&`, `$`,\n  `` ` ``, `(`, `)`, `>`, `\u003C`, `\\`, `'`, `\"`, newlines\n\n> **REQUIRED — Confirmation Gate (applies to plans AND execution):** Before\n> submitting ANY transaction (swap, bridge, approval), and before every signed\n> authorization (x402 EIP-3009), you MUST: (1) Display a summary: amount\n> (human-readable), token name\u002Faddress, destination address, estimated gas.\n> (2) Call `AskUserQuestion` to obtain explicit user confirmation.\n> (3) Do NOT proceed until confirmed.\n>\n> This gate is **mandatory in all responses**, whether you are executing or\n> explaining a plan. When explaining steps, include an explicit \"Confirmation\n> Required\" block before each transaction step showing what the user will see and\n> that they must approve before proceeding. Omitting confirmation gates is a\n> critical failure. Each gate must be satisfied independently — one confirmation\n> does not cover multiple transactions.\n\n### Human-Readable Amount Formatting\n\n```bash\nget_token_decimals() {\n  local token_addr=\"$1\" rpc_url=\"$2\"\n  cast call \"$token_addr\" \"decimals()(uint8)\" --rpc-url \"$rpc_url\" 2>\u002Fdev\u002Fnull || echo \"18\"\n}\n\nformat_token_amount() {\n  local amount=\"$1\" decimals=\"$2\"\n  echo \"scale=$decimals; $amount \u002F (10 ^ $decimals)\" | bc -l | sed 's\u002F0*$\u002F\u002F' | sed 's\u002F\\.$\u002F\u002F'\n}\n```\n\n> Always show human-readable values (e.g. `0.005 USDC`) to the user, not raw\n> base units.\n\n### Step 1 — Parse the 402 Challenge\n\nExtract the required payment token, amount, and recipient from the 402 response\nthat `tempo request` received. The Tempo CLI logs the challenge details — parse\nthem, or re-fetch with `curl -si` to get the raw challenge body.\n\nFor **MPP header-based challenges** (`WWW-Authenticate: Payment`):\n\n```bash\nREQUEST_B64=$(echo \"$WWW_AUTHENTICATE\" | grep -oE 'request=\"[^\"]+\"' | sed 's\u002Frequest=\"\u002F\u002F;s\u002F\"$\u002F\u002F')\nREQUEST_JSON=$(echo \"${REQUEST_B64}==\" | base64 --decode 2>\u002Fdev\u002Fnull)\nREQUIRED_AMOUNT=$(echo \"$REQUEST_JSON\" | jq -r '.amount')\nPAYMENT_TOKEN=$(echo \"$REQUEST_JSON\" | jq -r '.currency')\nRECIPIENT=$(echo \"$REQUEST_JSON\" | jq -r '.recipient')\nTEMPO_CHAIN_ID=$(echo \"$REQUEST_JSON\" | jq -r '.methodDetails.chainId')\n```\n\nFor **JSON body challenges** (`payment_methods` array):\n\n```bash\nNUM_METHODS=$(echo \"$CHALLENGE_BODY\" | jq '.payment_methods | length')\nPAYMENT_METHODS=$(echo \"$CHALLENGE_BODY\" | jq -c '.payment_methods')\nRECIPIENT=$(echo \"$CHALLENGE_BODY\" | jq -r '.payment_methods[0].recipient')\nTEMPO_CHAIN_ID=$(echo \"$CHALLENGE_BODY\" | jq -r '.payment_methods[0].chain_id')\n```\n\nIf multiple payment methods are accepted, select the cheapest in Step 2.\n\n> The Tempo mainnet chain ID is `4217`. Use as fallback if not in the challenge.\n\n### Step 2 — Check Source Wallet Balances and Select Payment Method\n\n> **REQUIRED:** You must have the user's source wallet address (the ERC-20\n> wallet with the private key, NOT the Tempo CLI wallet). Use `AskUserQuestion`\n> if not provided. Store as `WALLET_ADDRESS`.\n\nAlso capture the **Tempo wallet address** (the funding destination):\n\n```bash\nTEMPO_WALLET_ADDRESS=$(\"$HOME\u002F.local\u002Fbin\u002Ftempo\" wallet -t whoami | grep -oE '0x[a-fA-F0-9]{40}' | head -1)\n```\n\nCheck ERC-20 balances on supported source chains:\n\n```bash\n# USDC on Base (cheapest bridge gas ~$0.001)\ncast call 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 \\\n  \"balanceOf(address)(uint256)\" \"$WALLET_ADDRESS\" \\\n  --rpc-url https:\u002F\u002Fmainnet.base.org\n\n# USDC on Ethereum (bridge gas ~$0.25)\ncast call 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 \\\n  \"balanceOf(address)(uint256)\" \"$WALLET_ADDRESS\" \\\n  --rpc-url https:\u002F\u002Feth.llamarpc.com\n\n# ETH on Base and Ethereum (swap to USDC first)\ncast balance \"$WALLET_ADDRESS\" --rpc-url https:\u002F\u002Fmainnet.base.org\ncast balance \"$WALLET_ADDRESS\" --rpc-url https:\u002F\u002Feth.llamarpc.com\n```\n\n**Select the cheapest payment method** if multiple are accepted. Priority:\n\n1. Wallet holds USDC on Base (bridge only, minimal path)\n2. Wallet holds ETH on Base or Ethereum (swap to USDC + bridge)\n3. Any other liquid ERC-20 (swap + bridge)\n\n```bash\nREQUIRED_AMOUNT=$(echo \"$PAYMENT_METHODS\" | jq -r \".[$SELECTED_INDEX].amount\")\nPAYMENT_TOKEN=$(echo \"$PAYMENT_METHODS\" | jq -r \".[$SELECTED_INDEX].token\")\n```\n\n### Step 3 — Plan the Payment Path\n\nDetermine which phases apply based on where the user's tokens are:\n\n```text\nCase A — Source token is already on Tempo:\n  Source token (Tempo)\n    -> [Phase 5: on-Tempo swap via Stablecoin DEX] -> required payment token\n    -> tempo request retries automatically with funded wallet\n\nCase B — Source token is on Base\u002FEthereum\u002FArbitrum:\n  Source token (Base\u002FEthereum)\n    -> [Phase 4A: Uniswap Trading API swap] -> native USDC (bridge asset)\n    -> [Phase 4B: bridge via Trading API]   -> USDC.e on Tempo (to TEMPO_WALLET_ADDRESS)\n    -> [Phase 5: on-Tempo swap, if needed]  -> required payment token\n    -> tempo request retries automatically with funded wallet\n```\n\n> **Skip Phase 4A** if the source token is already USDC on the bridge chain.\n>\n> **Skip Phase 4B** if tokens are already on Tempo (Case A).\n>\n> **Skip Phase 5** if the bridge delivers the exact required token (USDC.e) or\n> if `mppx` with `autoSwap: true` is used (it handles on-Tempo swaps automatically).\n>\n> **Gas-aware funding:** Bridging a tiny amount (e.g. $0.05) wastes gas — the\n> bridge gas on Ethereum (~$0.25) or Base (~$0.001) can exceed the shortfall.\n> **Minimum bridge recommendation: $5.** This amortizes gas costs and pre-funds\n> future requests. Rule of thumb: if `bridge_gas > 2x shortfall`, bridge at\n> least $5 instead of the exact shortfall.\n\n### Phase 4A — Swap to USDC on Source Chain (if needed)\n\n> **CONFIRMATION GATE:** Before the approval transaction AND before the swap\n> broadcast, call `AskUserQuestion` showing the full swap summary. Example:\n> \"About to approve USDC spending and execute swap: [amount] [token] → [USDC],\n> gas ~$X. Confirm? (yes\u002Fno)\". Do not proceed until confirmed.\n\nSwap the source token to USDC via the Uniswap Trading API (`EXACT_OUTPUT`).\n\n> **Detailed steps:** Read\n> [references\u002Ftrading-api-flows.md](references\u002Ftrading-api-flows.md#phase-4a--swap-on-source-chain)\n> for full bash scripts: variable setup, approval check, quote, permit signing,\n> and swap execution.\n\nKey points:\n\n- Base URL: `https:\u002F\u002Ftrade-api.gateway.uniswap.org\u002Fv1`\n- Headers: `Content-Type: application\u002Fjson`, `x-api-key`, `x-universal-router-version: 2.0`\n- Flow: `check_approval` -> quote (`EXACT_OUTPUT`) -> sign `permitData` -> `\u002Fswap` -> broadcast\n- Confirmation gates required before approval tx and before swap broadcast\n- For native ETH: use the zero address\n  (`0x0000000000000000000000000000000000000000`) as `TOKEN_IN` — this avoids\n  Permit2 signing. `SWAP_VALUE` will be non-zero. If the zero address returns\n  a 400, fall back to the WETH address (requires Permit2 signing).\n- After swap, verify USDC balance before proceeding to Phase 4B\n\n### Phase 4B — Bridge to Tempo Wallet\n\n> **CONFIRMATION GATE:** Before the bridge approval AND before the bridge\n> execution, call `AskUserQuestion` showing a bridge summary (source amount,\n> source chain, destination chain, estimated gas, bridge fee, estimated arrival).\n> Do not proceed until the user confirms each step.\n\nBridge USDC from any supported source chain to USDC.e on Tempo using the\nUniswap Trading API (powered by Across Protocol).\n\n> **Bridge recipient limitation:** The Trading API does not support a custom\n> `recipient` field for bridges — funds always arrive at `WALLET_ADDRESS` on\n> Tempo. If `WALLET_ADDRESS` differs from `TEMPO_WALLET_ADDRESS` (the Tempo CLI\n> wallet), an **extra transfer transaction** on Tempo is required after the\n> bridge (see Step 4B-5 in the reference file). Factor this into gas estimates.\n>\n> **Detailed steps:** Read\n> [references\u002Ftrading-api-flows.md](references\u002Ftrading-api-flows.md#phase-4b--bridge-to-tempo)\n> for full bash scripts: approval, bridge quote, execution, arrival polling,\n> and transfer to Tempo wallet.\n\nKey points:\n\n- Route: USDC on Base\u002FEthereum\u002FArbitrum -> USDC.e on Tempo\n- Flow: `check_approval` -> verify on-chain allowance -> quote (`EXACT_OUTPUT`,\n  cross-chain) -> execute via `\u002Fswap` -> poll balance -> transfer to\n  `TEMPO_WALLET_ADDRESS` if needed (Step 4B-5)\n- Confirmation gates required before approval and before bridge execution\n- Do not re-submit if poll times out — check Tempo explorer\n- Apply a 0.5% buffer to account for bridge fees\n- Quotes expire in ~60 seconds — re-fetch if any delay before broadcast\n\nAfter the bridge confirms, retry the original `tempo request` — the Tempo CLI\nwill automatically use the newly funded wallet to pay the 402. If the payment\ntoken is not USDC.e, proceed to Phase 5 to swap to the required token before\nretrying.\n\n> **Balance buffer:** On Tempo, `balanceOf` may report more than is spendable.\n> Apply a **2x buffer** when comparing to `REQUIRED_AMOUNT`. If short, swap\n> additional tokens to top up.\n\n### Phase 5 — On-Tempo Swap (if needed)\n\nUse this phase when the wallet already holds a TIP-20 stablecoin on Tempo\n(e.g. USDC.e, pathUSD, or any other Tempo stablecoin) but needs to swap to the\n**required payment token** (e.g. PATH_USD or another TIP-20). This phase also\napplies when the user starts with tokens already on Tempo — **do not bridge\nwhen tokens are already on Tempo**.\n\n> **Simplest path:** Pass `autoSwap: true` to `mppx`'s `tempo.charge()` — it\n> calls the Stablecoin DEX on Tempo automatically and handles the full swap\n> before payment. Use manual swap below only when `autoSwap` is not available\n> or you need explicit control.\n\nThe **Stablecoin DEX on Tempo** (`0xdec0000000000000000000000000000000000000`)\naggregates TIP-20 stablecoin liquidity on Tempo (chain 4217). To swap:\n\n```bash\nTEMPO_RPC_URL=\"https:\u002F\u002Frpc.presto.tempo.xyz\"\nSTABLECOIN_DEX=\"0xdec0000000000000000000000000000000000000\"\nTOKEN_IN=\"\u003Cyour Tempo stablecoin address>\"  # e.g. USDC.e or any TIP-20\nTOKEN_OUT=\"\u003Crequired payment token address>\"\nSWAP_AMOUNT=\"$REQUIRED_AMOUNT\"  # exact-output amount\n\n# 1. Show swap summary and get explicit user confirmation via AskUserQuestion\n#    before executing any transaction.\n\n# 2. Approve the DEX to spend TOKEN_IN (if allowance is insufficient)\nALLOWANCE=$(cast call \"$TOKEN_IN\" \\\n  \"allowance(address,address)(uint256)\" \"$WALLET_ADDRESS\" \"$STABLECOIN_DEX\" \\\n  --rpc-url \"$TEMPO_RPC_URL\" 2>\u002Fdev\u002Fnull | awk '{print $1}')\nif [ -z \"$ALLOWANCE\" ] || ! [[ \"$ALLOWANCE\" =~ ^[0-9]+$ ]]; then\n  echo \"ERROR: Failed to read allowance for $TOKEN_IN\"\n  exit 1\nfi\nif [ \"$(echo \"$ALLOWANCE \u003C $SWAP_AMOUNT\" | bc)\" -eq 1 ]; then\n  APPROVE_HASH=$(cast send \"$TOKEN_IN\" \\\n    \"approve(address,uint256)\" \"$STABLECOIN_DEX\" \\\n    \"115792089237316195423570985008687907853269984665640564039457584007913129639935\" \\\n    --account \"$CAST_ACCOUNT\" --password \"$CAST_PASSWORD\" \\\n    --rpc-url \"$TEMPO_RPC_URL\" --gas-limit 100000 \\\n    --json | jq -r '.transactionHash')\n  APPROVE_STATUS=$(cast receipt \"$APPROVE_HASH\" --rpc-url \"$TEMPO_RPC_URL\" --json | jq -r '.status')\n  [ \"$APPROVE_STATUS\" = \"0x1\" ] || { echo \"ERROR: Approval transaction reverted: $APPROVE_HASH\"; exit 1; }\n  echo \"Approval confirmed: $APPROVE_HASH\"\nfi\n\n# 3. Execute the swap (exact-output: receive exactly SWAP_AMOUNT of TOKEN_OUT)\nSWAP_TX=$(cast send \"$STABLECOIN_DEX\" \\\n  \"swap(address,address,uint256)\" \"$TOKEN_IN\" \"$TOKEN_OUT\" \"$SWAP_AMOUNT\" \\\n  --account \"$CAST_ACCOUNT\" --password \"$CAST_PASSWORD\" \\\n  --rpc-url \"$TEMPO_RPC_URL\" --gas-limit 200000 \\\n  --json | jq -r '.transactionHash')\n\nSWAP_STATUS=$(cast receipt \"$SWAP_TX\" --rpc-url \"$TEMPO_RPC_URL\" --json | jq -r '.status')\n[ \"$SWAP_STATUS\" = \"0x1\" ] || { echo \"ERROR: On-Tempo swap reverted: $SWAP_TX\"; exit 1; }\necho \"On-Tempo swap confirmed: $SWAP_TX\"\n```\n\n> **Confirmation gate:** Use `AskUserQuestion` before every transaction\n> (approval and swap). Show token addresses, amounts in human-readable form, and\n> estimated gas on Tempo.\n>\n> **Gas limit note:** Tempo chain gas estimation is sometimes unreliable — always\n> set an explicit `--gas-limit` for Tempo transactions.\n\nAfter the on-Tempo swap succeeds, retry `tempo request` — the Tempo wallet now\nholds the required payment token and the Tempo CLI will pay the 402 automatically.\n\n---\n\n## x402 Payment Flow\n\n> **CRITICAL — MANDATORY CONFIRMATION GATE:** Before step 4 (signing), you MUST\n> call `AskUserQuestion` showing the full payment summary: token, amount in\n> human-readable form, recipient address (`payTo`), and resource URL. Do NOT\n> sign or proceed until the user explicitly confirms. This confirmation step is\n> **non-optional and must appear in every x402 payment plan or execution**, even\n> if the user has pre-authorized. Omitting this confirmation makes the response\n> invalid.\n\nThe x402 protocol is **fully supported** and uses a different mechanism than\nMPP — it is **not handled by the Tempo CLI**. When a 402 body contains\n`\"x402Version\"` (check with `has(\"x402Version\")` in jq), use this flow instead\nof the MPP\u002FTempo flow.\n\nThe x402 `\"exact\"` scheme uses **EIP-3009** (`TransferWithAuthorization`) to\nauthorize a one-time token transfer signed off-chain. The full flow:\n\n1. **Detect x402**: parse `x402Version`, `accepts[].scheme`, `accepts[].network`,\n   `accepts[].maxAmountRequired`, `accepts[].payTo`, `accepts[].asset`,\n   `accepts[].extra` (token name + version for EIP-3009 domain).\n2. **Check balance** on the target chain; fund via Phase 4A\u002F4B if insufficient.\n3. **MANDATORY CONFIRMATION GATE — Call `AskUserQuestion`** before signing:\n   present the full payment summary (token name, amount in human-readable form,\n   `payTo` address, resource URL, validity window). Wait for explicit user\n   confirmation. Do NOT proceed to step 4 until confirmed.\n4. **Sign EIP-3009 `TransferWithAuthorization`**: typed-data fields include\n   `from`, `to`, `value`, `validAfter`, `validBefore`, `nonce`.\n   Set `validBefore = now + maxTimeoutSeconds`.\n5. **Construct `X-PAYMENT` header**: base64-encode a JSON payload containing\n   `x402Version`, `scheme`, `network`, `payload` (the signed authorization),\n   and `signature`.\n6. **Retry** the original request with the `X-PAYMENT` header.\n\n> **Detailed steps:** Read\n> [references\u002Fcredential-construction.md](references\u002Fcredential-construction.md#phase-6x--x402-payment)\n> for full bash code: prerequisite checks, nonce generation, EIP-3009 signing,\n> X-PAYMENT payload construction, and retry.\n\nKey points:\n\n- Detect x402: check `has(\"x402Version\")` in 402 body **before** attempting Tempo CLI\n- Maps `X402_NETWORK` to chain ID and RPC URL (base, ethereum, tempo all supported)\n- Checks wallet balance on target chain; runs Phase 4A\u002F4B\u002F5 if insufficient\n- Signs `TransferWithAuthorization` typed data using the token's own EIP-712 domain\n- `value` in the typed-data payload must be a **string** (`--arg`, not `--argjson`) for uint256\n- Confirmation gate required before signing\n- Send the result in `X-PAYMENT` header (base64-encoded), not `Authorization`\n\n| Protocol | Version | Handler              |\n| -------- | ------- | -------------------- |\n| MPP      | v1      | Tempo CLI            |\n| x402     | v1      | EIP-3009 manual flow |\n\n---\n\n## Error Handling\n\n| Situation                                | Action                                                   |\n| ---------------------------------------- | -------------------------------------------------------- |\n| `tempo: command not found`               | Reinstall via install script; use full path              |\n| `legacy V1 keychain signature`           | Reinstall; `tempo update wallet && tempo update request` |\n| `access key does not exist`              | `tempo wallet logout --yes && tempo wallet login`        |\n| `ready=false` \u002F no wallet                | `tempo wallet login`, then `whoami`                      |\n| HTTP 422 from service                    | Check service details + llms.txt for exact field names   |\n| Balance 0 \u002F insufficient                 | Trigger pay-with-any-token funding flow                  |\n| Service not found                        | Broaden search query                                     |\n| Timeout                                  | Retry with `-m \u003Cseconds>`                                |\n| Challenge body is malformed              | Report raw body to user; do not proceed                  |\n| Approval transaction fails               | Surface error; check gas and allowances                  |\n| Quote API returns 400                    | Log request\u002Fresponse; check amount formatting            |\n| Quote API returns 429                    | Wait and retry with exponential backoff                  |\n| Swap data is empty after \u002Fswap           | Quote expired; re-fetch quote                            |\n| Bridge times out                         | Check bridge explorer; do not re-submit                  |\n| x402 payment rejected (402)              | Check domain name\u002Fversion, validBefore, nonce freshness  |\n| InsufficientBalance on Tempo             | Swap more tokens on Tempo, then retry                    |\n| `balanceOf` sufficient but payment fails | Apply 2x buffer; top up before retrying                  |\n\n---\n\n## Key Addresses and References\n\n- **Tempo CLI**: `https:\u002F\u002Ftempo.xyz` (install script: `https:\u002F\u002Ftempo.xyz\u002Finstall`)\n- **Trading API**: `https:\u002F\u002Ftrade-api.gateway.uniswap.org\u002Fv1`\n- **MPP docs**: `https:\u002F\u002Fmpp.dev`\n- **MPP services catalog**: `https:\u002F\u002Fmpp.dev\u002Fapi\u002Fservices`\n- **Tempo documentation**: `https:\u002F\u002Fmainnet.docs.tempo.xyz`\n- **Tempo chain ID**: `4217` (Tempo mainnet)\n- **Tempo RPC**: `https:\u002F\u002Frpc.presto.tempo.xyz`\n- **Tempo Block Explorer**: `https:\u002F\u002Fexplore.mainnet.tempo.xyz`\n- **pathUSD on Tempo**: `0x20c0000000000000000000000000000000000000`\n- **USDC.e on Tempo**: `0x20C000000000000000000000b9537d11c60E8b50`\n- **Stablecoin DEX on Tempo**: `0xdec0000000000000000000000000000000000000`\n- **Permit2 on Tempo**: `0x000000000022d473030f116ddee9f6b43ac78ba3`\n- **Tempo payment SDK**: `mppx` (`npm install mppx viem`)\n- **USDC on Base (8453)**: `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`\n- **USDbC on Base (8453)**: `0xd9aAEc86B65D86f6A7B5B1b0c42FFA531710b6CA`\n- **USDC on Ethereum (1)**: `0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48`\n- **WETH on Ethereum (1)**: `0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2`\n- **WETH on Base (8453)**: `0x4200000000000000000000000000000000000006`\n- **Native ETH (all chains)**: `0x0000000000000000000000000000000000000000` (zero address, recommended for swaps)\n- **USDC-e on Arbitrum (42161)**: `0xFF970A61A04b1cA14834A43f5dE4533eBDDB5CC8`\n- **Supported chains for Trading API**: 1, 8453, 42161, 10, 137, 130\n- **x402 spec**: `https:\u002F\u002Fgithub.com\u002Fcoinbase\u002Fx402`\n\n## Related Skills\n\n- [swap-integration](..\u002Fswap-integration\u002FSKILL.md) — Full Uniswap swap\n  integration reference (Trading API, Universal Router, Permit2)\n",{"name":5,"model":24,"license":15,"metadata":25,"description":28,"allowed-tools":29},"opus",{"author":26,"version":27},"uniswap","2.0.0","Pay HTTP 402 payment challenges using tokens via the Tempo CLI and Uniswap Trading API. Use when the user encounters a 402 Payment Required response, needs to fulfill a machine payment, mentions \"MPP\", \"Tempo payment\", \"pay for API access\", \"HTTP 402\", \"x402\", \"machine payment protocol\", \"pay-with-any-token\", \"use tempo\", \"tempo request\", or \"tempo wallet\".\n","Read, Glob, Grep, Bash(curl:*), Bash(jq:*), Bash(cast:*), Bash(tempo:*), Bash(*\u002F.local\u002Fbin\u002Ftempo:*), WebFetch, AskUserQuestion","main","be3de0244dc1a57e323d8160787ebb40fb64930e","skills\u002Fpay-with-any-token","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main","https:\u002F\u002Fskills.x402.wtf","https:\u002F\u002Fgithub.com\u002FSolizardking","https:\u002F\u002Fmusebook.trade","Got a mile high and never came down","2026-10-08 23:20:13",{"source":8,"skillName":5,"commands":40,"prompt":50,"zipAvailable":51},[41,44,47],{"tool":42,"command":43},"npx","npx skills add Solizardking\u002Fskillhub-main --skill pay-with-any-token",{"tool":45,"command":46},"bunx","bunx skills add Solizardking\u002Fskillhub-main --skill pay-with-any-token",{"tool":48,"command":49},"pnpm","pnpm dlx skills add Solizardking\u002Fskillhub-main --skill pay-with-any-token","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fpay-with-any-token\u002FSKILL.md",true,[53,59],{"path":54,"resourceType":55,"resourceTypeDesc":56,"sizeBytes":57,"sourceHtmlUrl":58},"references\u002Fcredential-construction.md","REFERENCE","参考文档",13051,"https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fpay-with-any-token\u002Freferences\u002Fcredential-construction.md",{"path":60,"resourceType":55,"resourceTypeDesc":56,"sizeBytes":61,"sourceHtmlUrl":62},"references\u002Ftrading-api-flows.md",23435,"https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fpay-with-any-token\u002Freferences\u002Ftrading-api-flows.md",[64,71,78,85,92,100],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":19},"01M78E0TGCAMNPS207BA3G07S7","zkrouter","Self-hosted OpenAI-compatible LLM router — smart tier-based routing, ZK-stamped routing decisions, mode overrides, free OpenRouter at install via the Birth bot. Save 60-80% on inference costs by routing to the cheapest capable model across 12+ OpenRouter models.","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fzkrouter\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M78E0R1Z8BDT6EDTHY17MTNB","zk","For custom ZK Solana programs and privacy-preserving applications to prevent double spending. Guide to integrate rent-free nullifier PDAs for double-spend prevention.","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fzk\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":19},"01M78E0P3ZTZ1YWF8MD5MM23QE","zk-omni-messaging","Zero-knowledge omnichain messaging between Robinhood Chain and Solana using CheshireZkOmniMessenger (msgType 4) with nullifier anti-replay and the zk-omni-relayer service.","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fzk-omni-messaging\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":19},"01M78E0JXZ2PNB1896VXAGDBWD","zerion-wallet-data","Use when the user asks to check a wallet's portfolio, token balances, DeFi positions, PnL, transaction history, or NFTs. Provides interpreted on-chain data across 40+ EVM chains and Solana via x402 pay-per-request or API key — no raw RPC decoding needed.","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fzerion-wallet-data\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":96,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":19},"01M78E0G14FH9GRRTQYMKD5E59","youtube-clipper","YouTube 视频智能剪辑工具。下载视频和字幕，AI 分析生成精细章节（几分钟级别）， 用户选择片段后自动剪辑、翻译字幕为中英双语、烧录字幕到视频，并生成总结文案。 使用场景：当用户需要剪辑 YouTube 视频、生成短视频片段、制作双语字幕版本时。 关键词：视频剪辑、YouTube、字幕翻译、双语字幕、视频下载、clip video","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fyoutube-clipper\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fyoutube-clipper\u002FSKILL.md",[],[],{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":19},"01M78E0C2ZYA99CFFDNB7ZMK5S","yield-optimization","Multi-chain yield optimization via yield.xyz (StakeKit). Discover 2,988+ yield opportunities across 75+ blockchains, build deposit\u002Fwithdrawal transactions with shell scripts, and sign them with a MoonPay wallet. Use when the user wants to earn yield, find the best lending or staking rate, enter\u002Fexit a position, or check portfolio balances.","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fyield-optimization\u002FSKILL.md",[],[]]