[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6H6FGE311RW1J4G58TY0JZN":3,"skill-same:01M6H6FGE311RW1J4G58TY0JZN":85},{"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":28,"publishedAt":49,"linkOnly":50,"markdownContent":51,"markdownBody":52,"frontMatter":53,"refName":57,"commitSha":58,"skillDirectory":59,"forksCount":60,"repositoryHtmlUrl":61,"repositoryHomepageUrl":6,"ownerHtmlUrl":62,"ownerBlogUrl":63,"ownerDescription":6,"updatedAt":64,"install":65,"resources":78},"01M6H6FGE311RW1J4G58TY0JZN","swap-integration",null,"Integrate Uniswap swaps into applications. Use when user says \"integrate swaps\", \"uniswap\", \"trading api\", \"add swap functionality\", \"build a swap frontend\", \"create a swap script\", \"smart contract swap integration\", \"use Universal Router\", \"Trading API\", or mentions swapping tokens via Uniswap.","0xharryriddle\u002Fcodex-field-kit","0xharryriddle","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F100945007?v=4","01M6H686JV0QKZYP2RWG6B2B8T","harryriddle","01M6H686PVZ8JGKWEG7B3GM5PD",3,"MIT","https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Farchive\u002Fupstream\u002Fchasebuild-agent-skills\u002Fweb3\u002Fskills\u002Fswap-integration\u002FSKILL.md",[18,23],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000009","前端开发","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000037","律师与法务","PROFESSION","适用职业",[29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48],"swap integration","integration","swap","router","opus","type","uniswap","tokens","swaps","expert","integrate","frontend","use","edit","write","read","subagent","applications","yarn","create","2026-11-10 10:12:30",false,"---\nname: swap-integration\ndescription: Integrate Uniswap swaps into applications. Use when user says \"integrate swaps\", \"uniswap\", \"trading api\", \"add swap functionality\", \"build a swap frontend\", \"create a swap script\", \"smart contract swap integration\", \"use Universal Router\", \"Trading API\", or mentions swapping tokens via Uniswap.\nallowed-tools: Read, Write, Edit, Glob, Grep, Bash(npm:*), Bash(npx:*), Bash(yarn:*), Bash(curl:*), WebFetch, Task(subagent_type:swap-integration-expert)\nmodel: opus\nlicense: MIT\nmetadata:\n  author: uniswap\n  version: '1.3.0'\n---\n\n# Swap Integration\n\nIntegrate Uniswap swaps into frontends, backends, and smart contracts.\n\n## Prerequisites\n\nThis skill assumes familiarity with viem basics (client setup, account management, contract interactions, transaction signing). Install the **uniswap-viem** plugin for comprehensive viem\u002Fwagmi guidance: `claude plugin add @uniswap\u002Funiswap-viem`\n\n## Quick Decision Guide\n\n| Building...                    | Use This Method               |\n| ------------------------------ | ----------------------------- |\n| Frontend with React\u002FNext.js    | Trading API                   |\n| Backend script or bot          | Trading API                   |\n| Smart contract integration     | Universal Router direct calls |\n| Need full control over routing | Universal Router SDK          |\n\n### Routing Types Quick Reference\n\n| Type     | Description                             | Chains                             |\n| -------- | --------------------------------------- | ---------------------------------- |\n| CLASSIC  | Standard AMM swap through Uniswap pools | All supported chains               |\n| DUTCH_V2 | UniswapX Dutch auction V2               | Ethereum, Arbitrum, Base, Unichain |\n| PRIORITY | MEV-protected priority order            | Base, Unichain                     |\n| WRAP     | ETH to WETH conversion                  | All                                |\n| UNWRAP   | WETH to ETH conversion                  | All                                |\n\nSee [Routing Types](#routing-types) for the complete list including DUTCH_V3, DUTCH_LIMIT, LIMIT_ORDER, BRIDGE, and QUICKROUTE.\n\n## Integration Methods\n\n### 1. Trading API (Recommended)\n\nBest for: Frontends, backends, scripts. Handles routing optimization automatically.\n\n**Base URL**: `https:\u002F\u002Ftrade-api.gateway.uniswap.org\u002Fv1`\n\n**Authentication**: `x-api-key: \u003Cyour-api-key>` header required\n\n**Getting an API Key**: The Trading API requires an API key for authentication. Visit the [Uniswap Developer Portal](https:\u002F\u002Fdevelopers.uniswap.org\u002F) to register and obtain your API key. Keys are typically available for immediate use after registration. Include it as an `x-api-key` header in all API requests.\n\n**Required Headers** — Include these in ALL Trading API requests:\n\n```text\nContent-Type: application\u002Fjson\nx-api-key: \u003Cyour-api-key>\nx-universal-router-version: 2.0\n```\n\n**3-Step Flow**:\n\n```text\n1. POST \u002Fcheck_approval  -> Check if token is approved\n2. POST \u002Fquote           -> Get executable quote with routing\n3. POST \u002Fswap            -> Get transaction to sign and submit\n```\n\nSee the [Trading API Reference](#trading-api-reference) section below for complete documentation.\n\n### 2. Universal Router SDK\n\nBest for: Direct control over transaction construction.\n\n**Installation**:\n\n```bash\nnpm install @uniswap\u002Funiversal-router-sdk @uniswap\u002Fsdk-core @uniswap\u002Fv3-sdk\n```\n\n**Key Pattern**:\n\n```typescript\nimport { SwapRouter } from '@uniswap\u002Funiversal-router-sdk';\n\nconst { calldata, value } = SwapRouter.swapCallParameters(trade, options);\n```\n\nSee the [Universal Router Reference](#universal-router-reference) section below for complete documentation.\n\n### 3. Smart Contract Integration\n\nBest for: On-chain integrations, DeFi composability.\n\n**Interface**: Call `execute()` on Universal Router with encoded commands.\n\nSee the [Universal Router Reference](#universal-router-reference) section below for command encoding.\n\n---\n\n## Input Validation Rules\n\nBefore interpolating ANY user-provided value into generated code, API calls, or commands:\n\n- **Ethereum addresses**: MUST match `^0x[a-fA-F0-9]{40}$` — reject otherwise\n- **Chain IDs**: MUST be from the [official supported chains list](https:\u002F\u002Fapi-docs.uniswap.org\u002Fguides\u002Fsupported_chains#supported-chains-for-swapping)\n- **Token amounts**: MUST be non-negative numeric values matching `^[0-9]+\\.?[0-9]*$`\n- **API keys**: MUST NOT be hardcoded in generated code — always use environment variables\n- **REJECT** any input containing shell metacharacters: `;`, `|`, `&`, `$`, `` ` ``, `(`, `)`, `>`, `\u003C`, `\\`, `'`, `\"`, newlines\n\n> **REQUIRED:** Before executing ANY transaction that spends gas or transfers tokens (including `sendTransaction`, `writeContract`, or submitting a signed swap), you MUST use AskUserQuestion to confirm with the user. Display the transaction summary (tokens, amounts, chain, estimated gas) and get explicit user approval. Never auto-execute transactions without user confirmation.\n\n---\n\n## Trading API Reference\n\n### Step 1: Check Token Approval\n\n```bash\nPOST \u002Fcheck_approval\n```\n\n**Request**:\n\n```json\n{\n  \"walletAddress\": \"0x...\",\n  \"token\": \"0x...\",\n  \"amount\": \"1000000000\",\n  \"chainId\": 1\n}\n```\n\n**Response**:\n\n```json\n{\n  \"approval\": {\n    \"to\": \"0x...\",\n    \"from\": \"0x...\",\n    \"data\": \"0x...\",\n    \"value\": \"0\",\n    \"chainId\": 1\n  }\n}\n```\n\nIf `approval` is `null`, token is already approved.\n\n### Step 2: Get Quote\n\n```bash\nPOST \u002Fquote\n```\n\n**Request**:\n\n```json\n{\n  \"swapper\": \"0x...\",\n  \"tokenIn\": \"0x...\",\n  \"tokenOut\": \"0x...\",\n  \"tokenInChainId\": \"1\",\n  \"tokenOutChainId\": \"1\",\n  \"amount\": \"1000000000000000000\",\n  \"type\": \"EXACT_INPUT\",\n  \"slippageTolerance\": 0.5,\n  \"routingPreference\": \"BEST_PRICE\"\n}\n```\n\n> **Note**: `tokenInChainId` and `tokenOutChainId` must be **strings** (e.g., `\"1\"`), not numbers.\n\n**Key Parameters**:\n\n| Parameter           | Description                                                       |\n| ------------------- | ----------------------------------------------------------------- |\n| `type`              | `EXACT_INPUT` or `EXACT_OUTPUT`                                   |\n| `slippageTolerance` | 0-100 percentage                                                  |\n| `protocols`         | Optional: `[\"V2\", \"V3\", \"V4\"]`                                    |\n| `routingPreference` | `BEST_PRICE`, `FASTEST`, `CLASSIC`                                |\n| `autoSlippage`      | `true` to auto-calculate slippage (overrides `slippageTolerance`) |\n| `urgency`           | `normal` or `fast` — affects UniswapX auction timing              |\n\n**Response** — the shape differs by routing type. `BEST_PRICE` routing on Ethereum mainnet typically returns UniswapX (DUTCH_V2), not CLASSIC.\n\n**CLASSIC response**:\n\n```json\n{\n  \"routing\": \"CLASSIC\",\n  \"quote\": {\n    \"input\": { \"token\": \"0x...\", \"amount\": \"1000000000000000000\" },\n    \"output\": { \"token\": \"0x...\", \"amount\": \"999000000\" },\n    \"slippage\": 0.5,\n    \"route\": [],\n    \"gasFee\": \"5000000000000000\",\n    \"gasFeeUSD\": \"0.01\",\n    \"gasUseEstimate\": \"150000\"\n  },\n  \"permitData\": null\n}\n```\n\n**UniswapX (DUTCH_V2\u002FV3\u002FPRIORITY) response** — different `quote` shape, no `quote.output`:\n\n```json\n{\n  \"routing\": \"DUTCH_V2\",\n  \"quote\": {\n    \"orderInfo\": {\n      \"reactor\": \"0x...\",\n      \"swapper\": \"0x...\",\n      \"nonce\": \"...\",\n      \"deadline\": 1772031054,\n      \"cosigner\": \"0x...\",\n      \"input\": {\n        \"token\": \"0x...\",\n        \"startAmount\": \"1000000000000000000\",\n        \"endAmount\": \"1000000000000000000\"\n      },\n      \"outputs\": [\n        {\n          \"token\": \"0x...\",\n          \"startAmount\": \"999000000\",\n          \"endAmount\": \"994000000\",\n          \"recipient\": \"0x...\"\n        }\n      ],\n      \"chainId\": 1\n    },\n    \"encodedOrder\": \"0x...\",\n    \"orderHash\": \"0x...\"\n  },\n  \"permitData\": { \"domain\": {}, \"types\": {}, \"values\": {} }\n}\n```\n\n> **UniswapX output amount**: Use `quote.orderInfo.outputs[0].startAmount` for the best-case fill amount. The `endAmount` is the floor after full auction decay. There is no `quote.output.amount` on UniswapX responses — accessing it will throw at runtime.\n>\n> **Display tip**: For CLASSIC routes, use `gasFeeUSD` (a string with the USD value) for gas cost display. Do **not** manually convert `gasFee` (wei) using a hardcoded ETH price — this leads to wildly inaccurate estimates (e.g., ~$87 instead of ~$0.01). UniswapX routes are gasless for the swapper.\n\nSee [QuoteResponse TypeScript Types](#7-quoteresponse-typescript-types) for compile-time type safety across routing types.\n\n### Step 3: Execute Swap\n\n```bash\nPOST \u002Fswap\n```\n\n**Request** - Spread the quote response directly into the body:\n\n```typescript\n\u002F\u002F CORRECT: Spread the quote response, strip null fields\nconst quoteResponse = await fetchQuote(params);\n\n\u002F\u002F Always strip permitData\u002FpermitTransaction — handle them explicitly by routing type\nconst { permitData, permitTransaction, ...cleanQuote } = quoteResponse;\nconst swapRequest: Record\u003Cstring, unknown> = { ...cleanQuote };\n\nconst isUniswapX =\n  quoteResponse.routing === 'DUTCH_V2' ||\n  quoteResponse.routing === 'DUTCH_V3' ||\n  quoteResponse.routing === 'PRIORITY';\n\nif (isUniswapX) {\n  \u002F\u002F UniswapX: signature only — permitData must NOT go to \u002Fswap\n  if (permit2Signature) swapRequest.signature = permit2Signature;\n} else {\n  \u002F\u002F CLASSIC: both signature and permitData, or neither\n  if (permit2Signature && permitData && typeof permitData === 'object') {\n    swapRequest.signature = permit2Signature;\n    swapRequest.permitData = permitData;\n  }\n}\n```\n\n**Critical**: Do NOT wrap the quote in `{quote: quoteResponse}`. The API expects the quote response fields spread into the request body.\n\n**Permit2 Rules** (CLASSIC routes):\n\n- `signature` and `permitData` must BOTH be present, or BOTH be absent\n- Never set `permitData: null` — omit the field entirely\n- The quote response often includes `permitData: null` — strip this before sending\n\n**UniswapX Routes** (DUTCH_V2\u002FV3\u002FPRIORITY): `permitData` is used locally to sign the order but must be **excluded** from the `\u002Fswap` body. See [Signing vs. Submission Flow](#uniswapx-signing-vs-submission-flow).\n\n**Response** (ready-to-sign transaction):\n\n```json\n{\n  \"swap\": {\n    \"to\": \"0x...\",\n    \"from\": \"0x...\",\n    \"data\": \"0x...\",\n    \"value\": \"0\",\n    \"chainId\": 1,\n    \"gasLimit\": \"250000\"\n  }\n}\n```\n\n**Response Validation** - Always validate before broadcasting:\n\n```typescript\nfunction validateSwapResponse(response: SwapResponse): void {\n  if (!response.swap?.data || response.swap.data === '' || response.swap.data === '0x') {\n    throw new Error('swap.data is empty - quote may have expired');\n  }\n  if (!isAddress(response.swap.to) || !isAddress(response.swap.from)) {\n    throw new Error('Invalid address in swap response');\n  }\n}\n```\n\n### Supported Chains\n\nSee the [official supported chains list](https:\u002F\u002Fapi-docs.uniswap.org\u002Fguides\u002Fsupported_chains#supported-chains-for-swapping) for the current set of chains and their IDs.\n\n### Routing Types\n\n| Type        | Description                                   |\n| ----------- | --------------------------------------------- |\n| CLASSIC     | Standard AMM swap through Uniswap pools       |\n| DUTCH_V2    | UniswapX Dutch auction V2                     |\n| DUTCH_V3    | UniswapX Dutch auction V3                     |\n| PRIORITY    | MEV-protected priority order (Base, Unichain) |\n| DUTCH_LIMIT | UniswapX Dutch limit order                    |\n| LIMIT_ORDER | Limit order                                   |\n| WRAP        | ETH to WETH conversion                        |\n| UNWRAP      | WETH to ETH conversion                        |\n| BRIDGE      | Cross-chain bridge                            |\n| QUICKROUTE  | Fast approximation quote                      |\n\n**UniswapX availability**: UniswapX V2 orders are supported on Ethereum (1), Arbitrum (42161), Base (8453), and Unichain (130). The auction mechanism varies by chain — see [UniswapX Auction Types](#uniswapx-auction-types) below.\n\n---\n\n## Critical Implementation Notes\n\nThese are common pitfalls discovered during real-world Trading API integration. **Follow these rules to avoid on-chain reverts and API errors.**\n\n### 1. Swap Request Body Format\n\nThe `\u002Fswap` endpoint expects the quote response **spread into the request body**, not wrapped in a `quote` field.\n\n```typescript\n\u002F\u002F WRONG - causes \"quote does not match any of the allowed types\"\nconst badRequest = {\n  quote: quoteResponse, \u002F\u002F Don't wrap!\n  signature: '0x...',\n};\n\n\u002F\u002F CORRECT - spread the quote response\nconst goodRequest = {\n  ...quoteResponse,\n  signature: '0x...', \u002F\u002F Only if using Permit2\n};\n```\n\n### 2. Null Field Handling\n\nThe API rejects `permitData: null`. Additionally, `permitData` handling differs by routing type — see [Signing vs. Submission Flow](#uniswapx-signing-vs-submission-flow) for the full explanation.\n\n```typescript\nfunction prepareSwapRequest(quoteResponse: QuoteResponse, signature?: string): object {\n  \u002F\u002F Always strip permitData and permitTransaction from the spread — handle them explicitly\n  const { permitData, permitTransaction, ...cleanQuote } = quoteResponse;\n  const request: Record\u003Cstring, unknown> = { ...cleanQuote };\n\n  \u002F\u002F UniswapX (DUTCH_V2, DUTCH_V3, PRIORITY): permitData is for LOCAL signing only.\n  \u002F\u002F The \u002Fswap body must NOT include permitData — the order is encoded in\n  \u002F\u002F quote.encodedOrder. Only the signature is needed.\n  const isUniswapX =\n    quoteResponse.routing === 'DUTCH_V2' ||\n    quoteResponse.routing === 'DUTCH_V3' ||\n    quoteResponse.routing === 'PRIORITY';\n\n  if (isUniswapX) {\n    if (signature) request.signature = signature;\n  } else {\n    \u002F\u002F CLASSIC: both signature and permitData required together, or both omitted.\n    \u002F\u002F The Universal Router contract needs permitData to verify the Permit2\n    \u002F\u002F authorization on-chain.\n    if (signature && permitData && typeof permitData === 'object') {\n      request.signature = signature;\n      request.permitData = permitData;\n    }\n  }\n\n  return request;\n}\n```\n\n### 3. Permit2 Field Rules\n\nThe rules for `signature` and `permitData` in the `\u002Fswap` request body depend on the routing type:\n\n**CLASSIC routes**:\n\n| Scenario                   | `signature` | `permitData` |\n| -------------------------- | ----------- | ------------ |\n| Standard swap (no Permit2) | Omit        | Omit         |\n| Permit2 swap               | Required    | Required     |\n| **Invalid**                | Present     | Missing      |\n| **Invalid**                | Missing     | Present      |\n| **Invalid (API error)**    | Any         | `null`       |\n\n**UniswapX routes (DUTCH_V2\u002FV3\u002FPRIORITY)**:\n\n| Scenario       | `signature` | `permitData`             |\n| -------------- | ----------- | ------------------------ |\n| UniswapX order | Required    | **Omit** (do not send)   |\n| **Invalid**    | Any         | Present (schema rejects) |\n\n### 4. Pre-Broadcast Validation\n\nAlways validate the swap response before sending to the blockchain:\n\n```typescript\nimport { isAddress, isHex } from 'viem';\n\nfunction validateSwapBeforeBroadcast(swap: SwapTransaction): void {\n  \u002F\u002F 1. data must be non-empty hex\n  if (!swap.data || swap.data === '' || swap.data === '0x') {\n    throw new Error('swap.data is empty - this will revert on-chain. Re-fetch the quote.');\n  }\n\n  if (!isHex(swap.data)) {\n    throw new Error('swap.data is not valid hex');\n  }\n\n  \u002F\u002F 2. Addresses must be valid\n  if (!isAddress(swap.to)) {\n    throw new Error('swap.to is not a valid address');\n  }\n\n  if (!isAddress(swap.from)) {\n    throw new Error('swap.from is not a valid address');\n  }\n\n  \u002F\u002F 3. Value must be present (can be \"0\" for non-ETH swaps)\n  if (swap.value === undefined || swap.value === null) {\n    throw new Error('swap.value is missing');\n  }\n}\n```\n\n### 5. Browser Environment Setup\n\nWhen using viem\u002Fwagmi in browser environments, you need Node.js polyfills:\n\n**Install buffer polyfill**:\n\n```bash\nnpm install buffer\n```\n\n**Add to your entry file (before other imports)**:\n\n```typescript\n\u002F\u002F src\u002Fmain.tsx or src\u002Findex.tsx\nimport { Buffer } from 'buffer';\nglobalThis.Buffer = Buffer;\n\n\u002F\u002F Then your other imports\nimport React from 'react';\nimport { WagmiProvider } from 'wagmi';\n\u002F\u002F ...\n```\n\n**Vite configuration** (`vite.config.ts`):\n\n```typescript\nexport default defineConfig({\n  define: {\n    global: 'globalThis',\n  },\n  optimizeDeps: {\n    include: ['buffer'],\n  },\n  resolve: {\n    alias: {\n      buffer: 'buffer',\n    },\n  },\n});\n```\n\nWithout this setup, you'll see: `ReferenceError: Buffer is not defined`\n\n#### CORS Proxy Configuration\n\nThe Trading API does not support browser CORS preflight requests — `OPTIONS` requests return `415 Unsupported Media Type`. Direct `fetch()` calls from a browser will always fail. You **must** proxy API requests through your own server or dev server.\n\n**Vite dev proxy** (merge into the same `vite.config.ts` used for the Buffer polyfill above):\n\n```typescript\nexport default defineConfig({\n  server: {\n    proxy: {\n      '\u002Fapi\u002Funiswap': {\n        target: 'https:\u002F\u002Ftrade-api.gateway.uniswap.org\u002Fv1',\n        changeOrigin: true,\n        rewrite: (path) => path.replace(\u002F^\\\u002Fapi\\\u002Funiswap\u002F, ''),\n      },\n    },\n  },\n});\n```\n\nThen use `\u002Fapi\u002Funiswap\u002Fquote` instead of the full URL in your frontend code.\n\n**Vercel production proxy** (`vercel.json`):\n\n```json\n{\n  \"rewrites\": [\n    {\n      \"source\": \"\u002Fapi\u002Funiswap\u002F:path*\",\n      \"destination\": \"https:\u002F\u002Ftrade-api.gateway.uniswap.org\u002Fv1\u002F:path*\"\n    }\n  ]\n}\n```\n\n**Cloudflare Pages** (`public\u002F_redirects`):\n\n```text\n\u002Fapi\u002Funiswap\u002F* https:\u002F\u002Ftrade-api.gateway.uniswap.org\u002Fv1\u002F:splat 200\n```\n\n**Next.js** (`next.config.js`):\n\n```javascript\nmodule.exports = {\n  async rewrites() {\n    return [\n      {\n        source: '\u002Fapi\u002Funiswap\u002F:path*',\n        destination: 'https:\u002F\u002Ftrade-api.gateway.uniswap.org\u002Fv1\u002F:path*',\n      },\n    ];\n  },\n};\n```\n\nWithout a proxy, you'll see: `415 Unsupported Media Type` on preflight or CORS errors in the browser console.\n\n### 6. Quote Freshness\n\n- Quotes expire quickly (typically 30 seconds)\n- Always re-fetch if the user takes time to review\n- Use the `deadline` parameter to prevent stale execution\n- If `\u002Fswap` returns empty `data`, the quote likely expired\n\n### 7. QuoteResponse TypeScript Types\n\nThe quote response shape differs by routing type. Use a discriminated union on the `routing` field to get compile-time safety instead of casting to `any`:\n\n```typescript\ntype ClassicQuoteResponse = {\n  routing: 'CLASSIC' | 'WRAP' | 'UNWRAP';\n  quote: {\n    input: { token: string; amount: string };\n    output: { token: string; amount: string };\n    slippage: number;\n    route: unknown[];\n    gasFee: string;\n    gasFeeUSD: string;\n    gasUseEstimate: string;\n  };\n  permitData: Record\u003Cstring, unknown> | null;\n};\n\ntype DutchOrderOutput = {\n  token: string;\n  startAmount: string;\n  endAmount: string;\n  recipient: string;\n};\n\ntype UniswapXQuoteResponse = {\n  routing: 'DUTCH_V2' | 'DUTCH_V3' | 'PRIORITY';\n  quote: {\n    orderInfo: {\n      outputs: DutchOrderOutput[];\n      input: { token: string; startAmount: string; endAmount: string };\n      deadline: number;\n      nonce: string;\n    };\n    encodedOrder: string;\n    orderHash: string;\n  };\n  \u002F\u002F EIP-712 typed data — sign locally, do NOT send to \u002Fswap\n  permitData: Record\u003Cstring, unknown> | null;\n};\n\ntype QuoteResponse = ClassicQuoteResponse | UniswapXQuoteResponse;\n\n\u002F\u002F Type guard for routing-aware logic\nfunction isUniswapXQuote(q: QuoteResponse): q is UniswapXQuoteResponse {\n  return q.routing === 'DUTCH_V2' || q.routing === 'DUTCH_V3' || q.routing === 'PRIORITY';\n}\n\n\u002F\u002F Reading the output amount by routing type\nfunction getOutputAmount(q: QuoteResponse): string {\n  if (isUniswapXQuote(q)) {\n    const firstOutput = q.quote.orderInfo.outputs[0];\n    if (!firstOutput) throw new Error('UniswapX quote has no outputs');\n    \u002F\u002F startAmount = best-case fill; endAmount = floor after auction decay\n    return firstOutput.startAmount;\n  }\n  return q.quote.output.amount;\n}\n```\n\n---\n\n## Universal Router Reference\n\nThe Universal Router is a unified interface for swapping across Uniswap v2, v3, and v4.\n\n### Core Function\n\n```solidity\nfunction execute(\n    bytes calldata commands,\n    bytes[] calldata inputs,\n    uint256 deadline\n) external payable;\n```\n\n### Command Encoding\n\nEach command is a single byte:\n\n| Bits | Name     | Purpose                             |\n| ---- | -------- | ----------------------------------- |\n| 0    | flag     | Allow revert (1 = continue on fail) |\n| 1-2  | reserved | Use 0                               |\n| 3-7  | command  | Operation identifier                |\n\n### Swap Commands\n\n| Code | Command           | Description               |\n| ---- | ----------------- | ------------------------- |\n| 0x00 | V3_SWAP_EXACT_IN  | v3 swap with exact input  |\n| 0x01 | V3_SWAP_EXACT_OUT | v3 swap with exact output |\n| 0x08 | V2_SWAP_EXACT_IN  | v2 swap with exact input  |\n| 0x09 | V2_SWAP_EXACT_OUT | v2 swap with exact output |\n| 0x10 | V4_SWAP           | v4 swap                   |\n\n### Token Operations\n\n| Code | Command     | Description                |\n| ---- | ----------- | -------------------------- |\n| 0x04 | SWEEP       | Clear router token balance |\n| 0x05 | TRANSFER    | Send specific amount       |\n| 0x0b | WRAP_ETH    | ETH to WETH                |\n| 0x0c | UNWRAP_WETH | WETH to ETH                |\n\n### Permit2 Commands\n\n| Code | Command               | Description           |\n| ---- | --------------------- | --------------------- |\n| 0x02 | PERMIT2_TRANSFER_FROM | Single token transfer |\n| 0x03 | PERMIT2_PERMIT_BATCH  | Batch approval        |\n| 0x0a | PERMIT2_PERMIT        | Single approval       |\n\n### SDK Usage\n\n```typescript\nimport { SwapRouter, UniswapTrade } from '@uniswap\u002Funiversal-router-sdk'\nimport { TradeType } from '@uniswap\u002Fsdk-core'\n\n\u002F\u002F Build trade using v3-sdk or router-sdk\nconst trade = new RouterTrade({\n  v3Routes: [...],\n  tradeType: TradeType.EXACT_INPUT\n})\n\n\u002F\u002F Get calldata for Universal Router\nconst { calldata, value } = SwapRouter.swapCallParameters(trade, {\n  slippageTolerance: new Percent(50, 10000), \u002F\u002F 0.5%\n  recipient: walletAddress,\n  deadline: Math.floor(Date.now() \u002F 1000) + 1200 \u002F\u002F 20 min\n})\n\n\u002F\u002F Send transaction\nconst tx = await wallet.sendTransaction({\n  to: UNIVERSAL_ROUTER_ADDRESS,\n  data: calldata,\n  value\n})\n```\n\n---\n\n## Permit2 Integration\n\nPermit2 enables signature-based token approvals instead of on-chain approve() calls.\n\n### Approval Target: Permit2 vs Legacy (Direct to Router)\n\nThere are two approval paths. Choose based on your integration type:\n\n| Approach                    | Approve To       | Per-Swap Auth       | Best For                         |\n| --------------------------- | ---------------- | ------------------- | -------------------------------- |\n| **Permit2** (recommended)   | Permit2 contract | EIP-712 signature   | Frontends with user interaction  |\n| **Legacy** (direct approve) | Universal Router | None (pre-approved) | Backend services, smart accounts |\n\n**Permit2 flow** (frontend with user signing):\n\n1. User approves token to Permit2 contract (one-time)\n2. Each swap: user signs an EIP-712 permit message\n3. Universal Router uses the signature to transfer tokens via Permit2\n\n**Legacy flow** (backend services, ERC-4337 smart accounts):\n\n1. Approve token directly to the Universal Router address (one-time)\n2. Each swap: no additional authorization needed\n3. Simpler for automated systems that cannot sign EIP-712 messages\n\nUse the Trading API's `\u002Fcheck_approval` endpoint — it returns the correct approval target based on the routing type.\n\n### How It Works\n\n1. User approves Permit2 contract once (infinite approval)\n2. For each swap, user signs a message authorizing the transfer\n3. Universal Router uses signature to transfer tokens via Permit2\n\n### Two Modes\n\n| Mode              | Description                                |\n| ----------------- | ------------------------------------------ |\n| SignatureTransfer | One-time signature, no on-chain state      |\n| AllowanceTransfer | Time-limited allowance with on-chain state |\n\n### Integration Pattern\n\n```typescript\nimport { getContract, maxUint256, type Address } from 'viem';\n\nconst PERMIT2_ADDRESS = '0x000000000022D473030F116dDEE9F6B43aC78BA3' as const;\n\n\u002F\u002F Check if Permit2 approval exists\nconst allowance = await publicClient.readContract({\n  address: PERMIT2_ADDRESS,\n  abi: permit2Abi,\n  functionName: 'allowance',\n  args: [userAddress, tokenAddress, spenderAddress],\n});\n\n\u002F\u002F If not approved, user must approve Permit2 first\nif (allowance.amount \u003C requiredAmount) {\n  const hash = await walletClient.writeContract({\n    address: tokenAddress,\n    abi: erc20Abi,\n    functionName: 'approve',\n    args: [PERMIT2_ADDRESS, maxUint256],\n  });\n  await publicClient.waitForTransactionReceipt({ hash });\n}\n\n\u002F\u002F Then sign permit for the swap\nconst permitSignature = await signPermit(...);\n```\n\n---\n\n## UniswapX Auction Types\n\nUniswapX routes swaps through off-chain fillers who compete to execute orders at better prices than on-chain AMMs. The auction mechanism varies by chain.\n\n### Exclusive Dutch Auction (Ethereum)\n\n- Starts with an RFQ (Request for Quote) phase where permissioned quoters compete\n- Winning quoter receives **exclusive filling rights** for a set period\n- If the exclusive filler doesn't execute, falls back to an open Dutch auction where the price decays each block\n- Best for large swaps where MEV protection matters most\n\n**Trading API routing type**: `DUTCH_V2` or `DUTCH_V3`\n\n### Open Dutch Auction (Arbitrum)\n\n- Direct open auction without an RFQ phase\n- Fillers compete on-chain through a descending price mechanism\n- Leverages Arbitrum's fast 0.25-second block times for rapid price discovery\n- The **Unimind algorithm** sets auction parameters based on historical pair performance\n\n**Trading API routing type**: `DUTCH_V2`\n\n### Priority Gas Auction (Base, Unichain)\n\n- Fillers bid by submitting transactions with varying **priority fees** at a target block\n- Highest priority fee wins the right to fill the order\n- Exploits OP Stack's priority ordering mechanism\n- Effective on chains where block builders respect priority ordering\n\n**Trading API routing type**: `PRIORITY`\n\n### Key Properties (All Auction Types)\n\n- **Gasless for users** — fillers pay gas fees, incorporated into final pricing\n- **No cost on failure** — if a swap doesn't fill, the user pays nothing\n- **MEV protection** — auction mechanics prevent frontrunning and sandwich attacks\n- UniswapX V2 is currently supported on Ethereum (1), Arbitrum (42161), Base (8453), and Unichain (130)\n\nFor more detail, see the [UniswapX Auction Types documentation](https:\u002F\u002Fdocs.uniswap.org\u002Fcontracts\u002Funiswapx\u002Fauctiontypes).\n\n### UniswapX: Signing vs. Submission Flow\n\nThe `permitData` field in the quote response serves different purposes depending on the routing type. Conflating the two causes `RequestValidationError` on `\u002Fswap`.\n\n**CLASSIC flow** — `permitData` goes to the server:\n\n1. `\u002Fquote` returns `permitData` (EIP-712 typed data for the Permit2 allowance)\n2. User signs `permitData` locally → produces `signature`\n3. `\u002Fswap` body includes **both** `signature` and `permitData` — the Universal Router contract needs `permitData` to reconstruct and verify the Permit2 authorization on-chain\n\n**UniswapX flow (DUTCH_V2\u002FV3\u002FPRIORITY)** — `permitData` stays local:\n\n1. `\u002Fquote` returns `permitData` (EIP-712 typed data for the Dutch order)\n2. User signs `permitData` locally → produces `signature`\n3. `\u002Fswap` body includes **only** `signature` — the order is already fully encoded in `quote.encodedOrder`, which the off-chain filler system reads directly. Sending `permitData` to `\u002Fswap` causes a schema validation error.\n\n| Route Type           | Sign with `permitData`? | Send `permitData` to `\u002Fswap`? | Send `signature` to `\u002Fswap`? |\n| -------------------- | ----------------------- | ----------------------------- | ---------------------------- |\n| CLASSIC              | Yes                     | **Yes** (router needs it)     | Yes (if using Permit2)       |\n| DUTCH_V2\u002FV3\u002FPRIORITY | Yes                     | **No** (schema rejects it)    | Yes                          |\n\n> **Common mistake**: The API error `\"quote\" does not match any of the allowed types` often points at the `quote` field, but the actual cause is `permitData` being present for a UniswapX route. Strip `permitData` before submitting — see the routing-aware `prepareSwapRequest` in [Null Field Handling](#2-null-field-handling).\n\n---\n\n## Direct Universal Router Integration (SDK)\n\nFor direct Universal Router integration without the Trading API, use the SDK's high-level API.\n\n### Installation\n\n```bash\nnpm install @uniswap\u002Funiversal-router-sdk @uniswap\u002Frouter-sdk @uniswap\u002Fsdk-core @uniswap\u002Fv3-sdk viem\n```\n\n### High-Level Approach (Recommended)\n\nUse `RouterTrade` + `SwapRouter.swapCallParameters()` for automatic command building:\n\n```typescript\nimport { SwapRouter } from '@uniswap\u002Funiversal-router-sdk';\nimport { Trade as RouterTrade } from '@uniswap\u002Frouter-sdk';\nimport { TradeType, Percent } from '@uniswap\u002Fsdk-core';\nimport { Route as V3Route, Pool } from '@uniswap\u002Fv3-sdk';\n\n\u002F\u002F 1. Fetch pool data (required to construct routes)\n\u002F\u002F Using viem to read on-chain pool state:\nconst slot0 = await publicClient.readContract({\n  address: poolAddress,\n  abi: [\n    {\n      name: 'slot0',\n      type: 'function',\n      stateMutability: 'view',\n      inputs: [],\n      outputs: [\n        { name: 'sqrtPriceX96', type: 'uint160' },\n        { name: 'tick', type: 'int24' },\n        { name: 'observationIndex', type: 'uint16' },\n        { name: 'observationCardinality', type: 'uint16' },\n        { name: 'observationCardinalityNext', type: 'uint16' },\n        { name: 'feeProtocol', type: 'uint8' },\n        { name: 'unlocked', type: 'bool' },\n      ],\n    },\n  ],\n  functionName: 'slot0',\n});\nconst liquidity = await publicClient.readContract({\n  address: poolAddress,\n  abi: [\n    {\n      name: 'liquidity',\n      type: 'function',\n      stateMutability: 'view',\n      inputs: [],\n      outputs: [{ type: 'uint128' }],\n    },\n  ],\n  functionName: 'liquidity',\n});\n\nconst pool = new Pool(tokenIn, tokenOut, fee, slot0[0].toString(), liquidity.toString(), slot0[1]);\n\n\u002F\u002F 2. Build route and trade\nconst route = new V3Route([pool], tokenIn, tokenOut);\nconst trade = RouterTrade.createUncheckedTrade({\n  route,\n  inputAmount: amountIn,\n  outputAmount: expectedOut,\n  tradeType: TradeType.EXACT_INPUT,\n});\n\n\u002F\u002F 3. Get calldata\nconst { calldata, value } = SwapRouter.swapCallParameters(trade, {\n  slippageTolerance: new Percent(50, 10000), \u002F\u002F 0.5%\n  recipient: walletAddress,\n  deadline: Math.floor(Date.now() \u002F 1000) + 1800,\n});\n\n\u002F\u002F 4. Execute with viem\nconst hash = await walletClient.sendTransaction({\n  to: UNIVERSAL_ROUTER_ADDRESS,\n  data: calldata,\n  value: BigInt(value),\n});\n```\n\n### Low-Level Approach (Manual Commands)\n\nFor custom flows (fee collection, complex routing), use `RoutePlanner` directly:\n\n```typescript\nimport { RoutePlanner, CommandType, ROUTER_AS_RECIPIENT } from '@uniswap\u002Funiversal-router-sdk';\nimport { encodeRouteToPath } from '@uniswap\u002Fv3-sdk';\n\n\u002F\u002F Special addresses\nconst MSG_SENDER = '0x0000000000000000000000000000000000000001';\nconst ADDRESS_THIS = '0x0000000000000000000000000000000000000002';\n```\n\n### Example: V3 Swap with Manual Commands\n\n```typescript\nimport { RoutePlanner, CommandType } from '@uniswap\u002Funiversal-router-sdk';\nimport { encodeRouteToPath, Route } from '@uniswap\u002Fv3-sdk';\n\nasync function swapV3Manual(route: Route, amountIn: bigint, amountOutMin: bigint) {\n  const planner = new RoutePlanner();\n\n  \u002F\u002F Encode V3 path from route\n  const path = encodeRouteToPath(route, false); \u002F\u002F false = exactInput\n\n  planner.addCommand(CommandType.V3_SWAP_EXACT_IN, [\n    MSG_SENDER, \u002F\u002F recipient\n    amountIn, \u002F\u002F amountIn\n    amountOutMin, \u002F\u002F amountOutMin\n    path, \u002F\u002F encoded path\n    true, \u002F\u002F payerIsUser\n  ]);\n\n  return executeRoute(planner);\n}\n```\n\n### Example: ETH to Token (Wrap + Swap)\n\n```typescript\nasync function swapEthToToken(route: Route, amountIn: bigint, amountOutMin: bigint) {\n  const planner = new RoutePlanner();\n  const path = encodeRouteToPath(route, false);\n\n  \u002F\u002F 1. Wrap ETH to WETH (keep in router)\n  planner.addCommand(CommandType.WRAP_ETH, [ADDRESS_THIS, amountIn]);\n\n  \u002F\u002F 2. Swap WETH → Token (payerIsUser = false since using router's WETH)\n  planner.addCommand(CommandType.V3_SWAP_EXACT_IN, [\n    MSG_SENDER,\n    amountIn,\n    amountOutMin,\n    path,\n    false,\n  ]);\n\n  return executeRoute(planner, { value: amountIn });\n}\n```\n\n### Example: Token to ETH (Swap + Unwrap)\n\n```typescript\nasync function swapTokenToEth(route: Route, amountIn: bigint, amountOutMin: bigint) {\n  const planner = new RoutePlanner();\n  const path = encodeRouteToPath(route, false);\n\n  \u002F\u002F 1. Swap Token → WETH (output to router)\n  planner.addCommand(CommandType.V3_SWAP_EXACT_IN, [\n    ADDRESS_THIS,\n    amountIn,\n    amountOutMin,\n    path,\n    true,\n  ]);\n\n  \u002F\u002F 2. Unwrap WETH to ETH\n  planner.addCommand(CommandType.UNWRAP_WETH, [MSG_SENDER, amountOutMin]);\n\n  return executeRoute(planner);\n}\n```\n\n### Example: Fee Collection with PAY_PORTION\n\n```typescript\nasync function swapWithFee(route: Route, amountIn: bigint, feeRecipient: Address, feeBips: number) {\n  const planner = new RoutePlanner();\n  const path = encodeRouteToPath(route, false);\n  const outputToken = route.output.wrapped.address;\n\n  \u002F\u002F Swap to router (ADDRESS_THIS)\n  planner.addCommand(CommandType.V3_SWAP_EXACT_IN, [ADDRESS_THIS, amountIn, 0n, path, true]);\n\n  \u002F\u002F Pay fee portion (e.g., 30 bips = 0.3%)\n  planner.addCommand(CommandType.PAY_PORTION, [outputToken, feeRecipient, feeBips]);\n\n  \u002F\u002F Sweep remainder to user\n  planner.addCommand(CommandType.SWEEP, [outputToken, MSG_SENDER, 0n]);\n\n  return executeRoute(planner);\n}\n```\n\n### Execute Route Helper\n\n```typescript\nimport { UNIVERSAL_ROUTER_ADDRESS } from '@uniswap\u002Funiversal-router-sdk';\n\nconst ROUTER_ABI = [\n  {\n    name: 'execute',\n    type: 'function',\n    stateMutability: 'payable',\n    inputs: [\n      { name: 'commands', type: 'bytes' },\n      { name: 'inputs', type: 'bytes[]' },\n      { name: 'deadline', type: 'uint256' },\n    ],\n    outputs: [],\n  },\n] as const;\n\nasync function executeRoute(planner: RoutePlanner, options?: { value?: bigint }) {\n  const deadline = BigInt(Math.floor(Date.now() \u002F 1000) + 1800);\n  const routerAddress = UNIVERSAL_ROUTER_ADDRESS('2.0', 1); \u002F\u002F version, chainId\n\n  const { request } = await publicClient.simulateContract({\n    address: routerAddress,\n    abi: ROUTER_ABI,\n    functionName: 'execute',\n    args: [planner.commands, planner.inputs, deadline],\n    account,\n    value: options?.value ?? 0n,\n  });\n\n  return walletClient.writeContract(request);\n}\n```\n\n### Command Cheat Sheet\n\n| Command           | Parameters                                               |\n| ----------------- | -------------------------------------------------------- |\n| V3_SWAP_EXACT_IN  | (recipient, amountIn, amountOutMin, path, payerIsUser)   |\n| V3_SWAP_EXACT_OUT | (recipient, amountOut, amountInMax, path, payerIsUser)   |\n| V2_SWAP_EXACT_IN  | (recipient, amountIn, amountOutMin, path[], payerIsUser) |\n| V2_SWAP_EXACT_OUT | (recipient, amountOut, amountInMax, path[], payerIsUser) |\n| WRAP_ETH          | (recipient, amount)                                      |\n| UNWRAP_WETH       | (recipient, amountMin)                                   |\n| SWEEP             | (token, recipient, amountMin)                            |\n| TRANSFER          | (token, recipient, amount)                               |\n| PAY_PORTION       | (token, recipient, bips)                                 |\n\n### Fee Tiers\n\n| Tier   | Value | Percentage |\n| ------ | ----- | ---------- |\n| LOWEST | 100   | 0.01%      |\n| LOW    | 500   | 0.05%      |\n| MEDIUM | 3000  | 0.30%      |\n| HIGH   | 10000 | 1.00%      |\n\n---\n\n## Common Integration Patterns\n\n### Frontend Swap Hook (React)\n\n**Note**: Ensure you've set up the Buffer polyfill and CORS proxy (see Critical Implementation Notes). For wagmi v2 `useWalletClient()` pitfalls, see [wagmi v2 Integration Pitfalls](#wagmi-v2-integration-pitfalls) below.\n\n```typescript\nimport { isAddress, isHex } from 'viem';\nimport { useWalletClient } from 'wagmi';\n\n\u002F\u002F In browser apps, use your CORS proxy path instead (see CORS Proxy Configuration)\n\u002F\u002F e.g., const API_URL = '\u002Fapi\u002Funiswap';\nconst API_URL = 'https:\u002F\u002Ftrade-api.gateway.uniswap.org\u002Fv1';\n\nfunction useSwap() {\n  const { data: walletClient } = useWalletClient();\n  const [quoteResponse, setQuoteResponse] = useState(null);\n  const [loading, setLoading] = useState(false);\n  const [error, setError] = useState(null);\n\n  const getQuote = async (params) => {\n    setLoading(true);\n    setError(null);\n    try {\n      const response = await fetch(`${API_URL}\u002Fquote`, {\n        method: 'POST',\n        headers: {\n          'Content-Type': 'application\u002Fjson',\n          'x-api-key': API_KEY,\n          'x-universal-router-version': '2.0',\n        },\n        body: JSON.stringify(params),\n      });\n      const data = await response.json();\n      if (!response.ok) throw new Error(data.detail || 'Quote failed');\n      setQuoteResponse(data); \u002F\u002F Store the FULL response, not just data.quote\n    } catch (err) {\n      setError(err.message);\n    } finally {\n      setLoading(false);\n    }\n  };\n\n  const executeSwap = async (permit2Signature?: string) => {\n    if (!quoteResponse) throw new Error('No quote available');\n\n    \u002F\u002F Strip null fields and spread quote response into body\n    const { permitData, permitTransaction, ...cleanQuote } = quoteResponse;\n    const swapRequest: Record\u003Cstring, unknown> = { ...cleanQuote };\n\n    \u002F\u002F CRITICAL: permitData handling differs by routing type\n    const isUniswapX =\n      quoteResponse.routing === 'DUTCH_V2' ||\n      quoteResponse.routing === 'DUTCH_V3' ||\n      quoteResponse.routing === 'PRIORITY';\n\n    if (isUniswapX) {\n      \u002F\u002F UniswapX: signature only — permitData must NOT be sent to \u002Fswap\n      \u002F\u002F (permitData is used locally to sign the order, not submitted to the API)\n      if (permit2Signature) swapRequest.signature = permit2Signature;\n    } else {\n      \u002F\u002F CLASSIC: both signature and permitData required together, or both omitted\n      if (permit2Signature && permitData && typeof permitData === 'object') {\n        swapRequest.signature = permit2Signature;\n        swapRequest.permitData = permitData;\n      }\n    }\n\n    const swapResponse = await fetch(`${API_URL}\u002Fswap`, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application\u002Fjson',\n        'x-api-key': API_KEY,\n        'x-universal-router-version': '2.0',\n      },\n      body: JSON.stringify(swapRequest),\n    });\n    const data = await swapResponse.json();\n    if (!swapResponse.ok) throw new Error(data.detail || 'Swap failed');\n\n    \u002F\u002F CRITICAL: Validate response before broadcasting\n    if (!data.swap?.data || data.swap.data === '' || data.swap.data === '0x') {\n      throw new Error('Empty swap data - quote may have expired. Please refresh.');\n    }\n\n    \u002F\u002F Send transaction via wallet (walletClient from useWalletClient())\n    if (!walletClient) throw new Error('Wallet not connected');\n    const tx = await walletClient.sendTransaction(data.swap);\n    return tx;\n  };\n\n  return { quote: quoteResponse?.quote, loading, error, getQuote, executeSwap };\n}\n```\n\n### wagmi v2 Integration Pitfalls\n\nThe `useWalletClient()` hook from wagmi v2 can return `undefined` even when the wallet is connected — it resolves asynchronously. This causes \"wallet not connected\" errors at swap time. Additionally, the returned client needs a `chain` for `sendTransaction()` to work.\n\n**Recommended pattern** — use `@wagmi\u002Fcore` action functions at swap time instead of hooks:\n\n```typescript\nimport { getWalletClient, getPublicClient, switchChain } from '@wagmi\u002Fcore';\nimport type { Config } from 'wagmi';\n\nasync function executeSwapTransaction(\n  config: Config,\n  chainId: number,\n  swapTx: { to: string; data: string; value: string }\n) {\n  \u002F\u002F 1. Ensure the wallet is on the correct chain\n  await switchChain(config, { chainId });\n\n  \u002F\u002F 2. Get wallet client with explicit chainId — avoids undefined and missing chain\n  const walletClient = await getWalletClient(config, { chainId });\n\n  \u002F\u002F 3. Execute the swap\n  const hash = await walletClient.sendTransaction({\n    to: swapTx.to as `0x${string}`,\n    data: swapTx.data as `0x${string}`,\n    value: BigInt(swapTx.value || '0'),\n  });\n\n  \u002F\u002F 4. Wait for confirmation\n  const publicClient = getPublicClient(config, { chainId });\n  if (!publicClient) throw new Error(`No public client configured for chainId ${chainId}`);\n  return publicClient.waitForTransactionReceipt({ hash });\n}\n```\n\n**Why this matters**:\n\n- `useWalletClient()` hook returns `{ data: undefined }` during async resolution, even after `useAccount()` shows connected\n- `getWalletClient(config, { chainId })` is a promise that resolves only when the client is ready, and includes the chain\n- `switchChain()` prevents \"chain mismatch\" errors when the wallet is on a different network than the swap\n\n### Backend Swap Script (Node.js)\n\n```typescript\nimport { createWalletClient, createPublicClient, http, isAddress, isHex, type Address } from 'viem';\nimport { privateKeyToAccount } from 'viem\u002Faccounts';\nimport { mainnet } from 'viem\u002Fchains';\n\nconst API_URL = 'https:\u002F\u002Ftrade-api.gateway.uniswap.org\u002Fv1';\nconst API_KEY = process.env.UNISWAP_API_KEY!;\n\nconst account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);\nconst publicClient = createPublicClient({ chain: mainnet, transport: http() });\nconst walletClient = createWalletClient({ account, chain: mainnet, transport: http() });\n\n\u002F\u002F Helper to prepare \u002Fswap request body — routing-aware permitData handling\nfunction prepareSwapRequest(quoteResponse: Record\u003Cstring, unknown>, signature?: string): object {\n  const { permitData, permitTransaction, ...cleanQuote } = quoteResponse;\n  const request: Record\u003Cstring, unknown> = { ...cleanQuote };\n\n  \u002F\u002F UniswapX (DUTCH_V2, DUTCH_V3, PRIORITY): permitData is for LOCAL signing only.\n  \u002F\u002F The \u002Fswap body must NOT include permitData — the order is already encoded\n  \u002F\u002F in quote.encodedOrder. Only the signature is needed.\n  const isUniswapX =\n    quoteResponse.routing === 'DUTCH_V2' ||\n    quoteResponse.routing === 'DUTCH_V3' ||\n    quoteResponse.routing === 'PRIORITY';\n\n  if (isUniswapX) {\n    if (signature) request.signature = signature;\n  } else {\n    \u002F\u002F CLASSIC: both signature and permitData required together, or both omitted\n    if (signature && permitData && typeof permitData === 'object') {\n      request.signature = signature;\n      request.permitData = permitData;\n    }\n  }\n\n  return request;\n}\n\n\u002F\u002F Validate swap response before broadcasting\nfunction validateSwap(swap: { data?: string; to?: string; from?: string }): void {\n  if (!swap?.data || swap.data === '' || swap.data === '0x') {\n    throw new Error('swap.data is empty - quote may have expired');\n  }\n  if (!isHex(swap.data)) {\n    throw new Error('swap.data is not valid hex');\n  }\n  if (!swap.to || !isAddress(swap.to) || !swap.from || !isAddress(swap.from)) {\n    throw new Error('Invalid address in swap response');\n  }\n}\n\nasync function executeSwap(tokenIn: Address, tokenOut: Address, amount: string, chainId: number) {\n  const ETH_ADDRESS = '0x0000000000000000000000000000000000000000';\n\n  \u002F\u002F 1. Check approval (for ERC20 tokens, not native ETH)\n  if (tokenIn !== ETH_ADDRESS) {\n    const approvalRes = await fetch(`${API_URL}\u002Fcheck_approval`, {\n      method: 'POST',\n      headers: {\n        'x-api-key': API_KEY,\n        'Content-Type': 'application\u002Fjson',\n        'x-universal-router-version': '2.0',\n      },\n      body: JSON.stringify({\n        walletAddress: account.address,\n        token: tokenIn,\n        amount,\n        chainId,\n      }),\n    });\n    const approvalData = await approvalRes.json();\n\n    if (approvalData.approval) {\n      const hash = await walletClient.sendTransaction({\n        to: approvalData.approval.to,\n        data: approvalData.approval.data,\n        value: BigInt(approvalData.approval.value || '0'),\n      });\n      await publicClient.waitForTransactionReceipt({ hash });\n    }\n  }\n\n  \u002F\u002F 2. Get quote\n  const quoteRes = await fetch(`${API_URL}\u002Fquote`, {\n    method: 'POST',\n    headers: {\n      'x-api-key': API_KEY,\n      'Content-Type': 'application\u002Fjson',\n      'x-universal-router-version': '2.0',\n    },\n    body: JSON.stringify({\n      swapper: account.address,\n      tokenIn,\n      tokenOut,\n      tokenInChainId: String(chainId),\n      tokenOutChainId: String(chainId),\n      amount,\n      type: 'EXACT_INPUT',\n      slippageTolerance: 0.5,\n    }),\n  });\n  const quoteResponse = await quoteRes.json(); \u002F\u002F Store FULL response\n\n  if (!quoteRes.ok) {\n    throw new Error(quoteResponse.detail || 'Quote failed');\n  }\n\n  \u002F\u002F 3. Execute swap - CRITICAL: spread quote response, strip null fields\n  const swapRequest = prepareSwapRequest(quoteResponse);\n\n  const swapRes = await fetch(`${API_URL}\u002Fswap`, {\n    method: 'POST',\n    headers: {\n      'x-api-key': API_KEY,\n      'Content-Type': 'application\u002Fjson',\n      'x-universal-router-version': '2.0',\n    },\n    body: JSON.stringify(swapRequest),\n  });\n  const swapData = await swapRes.json();\n\n  if (!swapRes.ok) {\n    throw new Error(swapData.detail || 'Swap request failed');\n  }\n\n  \u002F\u002F 4. Validate before broadcasting\n  validateSwap(swapData.swap);\n\n  const hash = await walletClient.sendTransaction({\n    to: swapData.swap.to,\n    data: swapData.swap.data,\n    value: BigInt(swapData.swap.value || '0'),\n  });\n  return publicClient.waitForTransactionReceipt({ hash });\n}\n```\n\n### Smart Contract Integration (Solidity)\n\n```solidity\n\u002F\u002F SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IUniversalRouter {\n    function execute(\n        bytes calldata commands,\n        bytes[] calldata inputs,\n        uint256 deadline\n    ) external payable;\n}\n\ninterface IERC20 {\n    function approve(address spender, uint256 amount) external returns (bool);\n}\n\ncontract SwapIntegration {\n    IUniversalRouter public immutable router;\n    address public constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;\n\n    constructor(address _router) {\n        router = IUniversalRouter(_router);\n    }\n\n    function swap(\n        bytes calldata commands,\n        bytes[] calldata inputs,\n        uint256 deadline\n    ) external payable {\n        router.execute{value: msg.value}(commands, inputs, deadline);\n    }\n\n    \u002F\u002F Approve token for Permit2 (one-time setup)\n    function approveToken(address token) external {\n        IERC20(token).approve(PERMIT2, type(uint256).max);\n    }\n}\n```\n\n---\n\n## Advanced Patterns\n\n### Smart Account Integration (ERC-4337)\n\nExecute Trading API swaps through ERC-4337 smart accounts with delegation. The pattern:\n\n1. Get swap calldata from Trading API (standard 3-step flow)\n2. Wrap the calldata in a delegation redemption execution\n3. Submit via bundler as a UserOperation\n\n```typescript\n\u002F\u002F After getting swap calldata from Trading API:\nconst { to, data, value } = swapResponse.swap;\n\n\u002F\u002F Wrap in delegation execution\nconst execution = {\n  target: to, \u002F\u002F Universal Router\n  callData: data,\n  value: BigInt(value),\n};\n\n\u002F\u002F Submit via bundler\nconst userOpHash = await bundlerClient.sendUserOperation({\n  account: delegateSmartAccount,\n  calls: [\n    {\n      to: delegationManagerAddress,\n      data: encodeFunctionData({\n        abi: delegationManagerAbi,\n        functionName: 'redeemDelegations',\n        args: [[[signedDelegation]], [0], [[execution]]],\n      }),\n      value: execution.value,\n    },\n  ],\n});\n```\n\n**Key considerations**:\n\n- Use legacy approvals (direct to Universal Router) instead of Permit2 for smart accounts — see [Approval Target](#approval-target-permit2-vs-legacy-direct-to-router)\n- Add 20-30% gas buffer for bundler gas estimation\n- Handle bundler-specific error codes separately from standard transaction errors\n\nSee [Advanced Patterns Reference](.\u002Freferences\u002Fadvanced-patterns.md#smart-account-integration-erc-4337) for the complete implementation with types and error handling.\n\n### WETH Handling on L2s\n\nOn L2 chains (Base, Optimism, Arbitrum), swaps outputting ETH may deliver WETH instead of native ETH. Always check and unwrap after swaps:\n\n```typescript\nimport { parseAbi, type Address } from 'viem';\n\nconst WETH_ABI = parseAbi([\n  'function balanceOf(address) view returns (uint256)',\n  'function withdraw(uint256)',\n]);\n\nconst WETH_ADDRESSES: Record\u003Cnumber, Address> = {\n  1: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',\n  10: '0x4200000000000000000000000000000000000006',\n  8453: '0x4200000000000000000000000000000000000006',\n  42161: '0x82aF49447D8a07e3bd95BD0d56f35241523fBab1',\n};\n\n\u002F\u002F After swap completes on an L2:\nconst wethAddress = WETH_ADDRESSES[chainId];\nif (wethAddress) {\n  const wethBalance = await publicClient.readContract({\n    address: wethAddress,\n    abi: WETH_ABI,\n    functionName: 'balanceOf',\n    args: [accountAddress],\n  });\n\n  if (wethBalance > 0n) {\n    const hash = await walletClient.writeContract({\n      address: wethAddress,\n      abi: WETH_ABI,\n      functionName: 'withdraw',\n      args: [wethBalance],\n    });\n    await publicClient.waitForTransactionReceipt({ hash });\n  }\n}\n```\n\nSee [Advanced Patterns Reference](.\u002Freferences\u002Fadvanced-patterns.md#weth-handling-on-l2s) for chain-specific WETH addresses and integration details.\n\n### Rate Limiting\n\nThe Trading API enforces rate limits (~10 requests\u002Fsecond per endpoint). For batch operations:\n\n- Add **100-200ms delays** between sequential API calls\n- Implement **exponential backoff with jitter** on 429 responses\n- **Cache approval results** — approvals rarely change between calls\n\n```typescript\n\u002F\u002F Exponential backoff for 429 responses\nasync function fetchWithRetry(url: string, init: RequestInit, maxRetries = 5): Promise\u003CResponse> {\n  for (let attempt = 0; attempt \u003C= maxRetries; attempt++) {\n    const response = await fetch(url, init);\n    if (response.status !== 429 && response.status \u003C 500) return response;\n    if (attempt === maxRetries) throw new Error(`Failed after ${maxRetries} retries`);\n\n    const delay = Math.min(200 * Math.pow(2, attempt) + Math.random() * 100, 10000);\n    await new Promise((resolve) => setTimeout(resolve, delay));\n  }\n  throw new Error('Unreachable');\n}\n```\n\nSee [Advanced Patterns Reference](.\u002Freferences\u002Fadvanced-patterns.md#rate-limiting-best-practices) for batch operation patterns and full retry implementation.\n\n---\n\n## Key Contract Addresses\n\n### Universal Router (v4)\n\nAddresses are per-chain. The legacy v1 address `0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD` is deprecated.\n\n| Chain       | ID      | Address                                      |\n| ----------- | ------- | -------------------------------------------- |\n| Ethereum    | 1       | `0x66a9893cc07d91d95644aedd05d03f95e1dba8af` |\n| Unichain    | 130     | `0xef740bf23acae26f6492b10de645d6b98dc8eaf3` |\n| Optimism    | 10      | `0x851116d9223fabed8e56c0e6b8ad0c31d98b3507` |\n| Base        | 8453    | `0x6ff5693b99212da76ad316178a184ab56d299b43` |\n| Arbitrum    | 42161   | `0xa51afafe0263b40edaef0df8781ea9aa03e381a3` |\n| Polygon     | 137     | `0x1095692a6237d83c6a72f3f5efedb9a670c49223` |\n| Blast       | 81457   | `0xeabbcb3e8e415306207ef514f660a3f820025be3` |\n| BNB         | 56      | `0x1906c1d672b88cd1b9ac7593301ca990f94eae07` |\n| Zora        | 7777777 | `0x3315ef7ca28db74abadc6c44570efdf06b04b020` |\n| World Chain | 480     | `0x8ac7bee993bb44dab564ea4bc9ea67bf9eb5e743` |\n| Avalanche   | 43114   | `0x94b75331ae8d42c1b61065089b7d48fe14aa73b7` |\n| Celo        | 42220   | `0xcb695bc5d3aa22cad1e6df07801b061a05a0233a` |\n| Soneium     | 1868    | `0x4cded7edf52c8aa5259a54ec6a3ce7c6d2a455df` |\n| Ink         | 57073   | `0x112908dac86e20e7241b0927479ea3bf935d1fa0` |\n| Monad       | 143     | `0x0d97dc33264bfc1c226207428a79b26757fb9dc3` |\n\nFor testnet addresses, see [Uniswap v4 Deployments](https:\u002F\u002Fdocs.uniswap.org\u002Fcontracts\u002Fv4\u002Fdeployments).\n\n### Permit2\n\n| Chain      | Address                                      |\n| ---------- | -------------------------------------------- |\n| All chains | `0x000000000022D473030F116dDEE9F6B43aC78BA3` |\n\n---\n\n## Troubleshooting\n\n### Common Issues\n\n| Issue                                                  | Solution                                                                                                                                                                                                     |\n| ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| \"Insufficient allowance\"                               | Call \u002Fcheck_approval first and submit approval tx                                                                                                                                                            |\n| \"Quote expired\"                                        | Increase deadline or re-fetch quote                                                                                                                                                                          |\n| \"Slippage exceeded\"                                    | Increase slippageTolerance or retry                                                                                                                                                                          |\n| \"Insufficient liquidity\"                               | Try smaller amount or different route                                                                                                                                                                        |\n| **\"Buffer is not defined\"**                            | Add Buffer polyfill (see Critical Implementation Notes)                                                                                                                                                      |\n| **On-chain revert with empty data**                    | Validate `swap.data` is non-empty hex before broadcasting                                                                                                                                                    |\n| **\"permitData must be of type object\"**                | Strip `permitData: null` from request - omit field entirely                                                                                                                                                  |\n| **\"quote does not match any of the allowed types\"**    | Don't wrap quote in `{quote: ...}` — spread into request body. Also check: for UniswapX routes, `permitData` must be omitted from the `\u002Fswap` body (see [API Validation Errors](#api-validation-errors-400)) |\n| **Received WETH instead of ETH on L2**                 | Check and unwrap WETH after swap (see [WETH Handling on L2s](#weth-handling-on-l2s))                                                                                                                         |\n| **429 Too Many Requests**                              | Implement exponential backoff and add delays between batch requests (see [Rate Limiting](#rate-limiting))                                                                                                    |\n| **415 on OPTIONS preflight \u002F CORS error**              | Set up a CORS proxy (see [CORS Proxy Configuration](#cors-proxy-configuration) in Browser Environment Setup)                                                                                                 |\n| **walletClient is undefined when wallet is connected** | Use `getWalletClient()` from `@wagmi\u002Fcore` instead of the `useWalletClient()` hook (see [wagmi v2 Integration Pitfalls](#wagmi-v2-integration-pitfalls))                                                     |\n| **\"Please provide a chain with the chain argument\"**   | Pass `chainId` to `getWalletClient(config, { chainId })`                                                                                                                                                     |\n| **Chain mismatch error on swap**                       | Call `switchChain()` before `getWalletClient()` (see [wagmi v2 Integration Pitfalls](#wagmi-v2-integration-pitfalls))                                                                                        |\n\n### API Validation Errors (400)\n\n| Error Message                                     | Cause                                                                    | Fix                                                                                                        |\n| ------------------------------------------------- | ------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------- |\n| `\"permitData\" must be of type object`             | Sending `permitData: null`                                               | Omit the field entirely when null                                                                          |\n| `\"quote\" does not match any of the allowed types` | Wrapping quote in `{quote: quoteResponse}`                               | Spread quote response: `{...quoteResponse}`                                                                |\n| `\"quote\" does not match any of the allowed types` | Including `permitData` in a UniswapX (DUTCH_V2\u002FV3\u002FPRIORITY) `\u002Fswap` body | Omit `permitData` for UniswapX routes — see [Signing vs. Submission](#uniswapx-signing-vs-submission-flow) |\n| `signature and permitData must both be present`   | Including only one Permit2 field (CLASSIC routes only)                   | Include both or neither for CLASSIC; omit `permitData` for UniswapX                                        |\n\n### API Error Codes\n\n| Code | Meaning                                                  |\n| ---- | -------------------------------------------------------- |\n| 400  | Invalid request parameters (see validation errors above) |\n| 401  | Invalid or missing API key                               |\n| 404  | No route found for pair                                  |\n| 429  | Rate limit exceeded                                      |\n| 500  | API error - implement exponential backoff retry          |\n\n### Pre-Broadcast Checklist\n\nBefore sending a swap transaction to the blockchain:\n\n1. **Verify `swap.data`** is non-empty hex (not `''`, not `'0x'`)\n2. **Verify addresses** - `swap.to` and `swap.from` are valid\n3. **Check quote freshness** - Re-fetch if older than 30 seconds\n4. **Validate gas** - Apply 10-20% buffer to estimates\n5. **Confirm balance** - User has sufficient token balance\n\n---\n\n## Additional Resources\n\n- [Universal Router GitHub](https:\u002F\u002Fgithub.com\u002FUniswap\u002Funiversal-router)\n- [Uniswap Docs](https:\u002F\u002Fdocs.uniswap.org)\n- [SDK Monorepo](https:\u002F\u002Fgithub.com\u002FUniswap\u002Fsdks)\n- [Permit2 Patterns](https:\u002F\u002Fgithub.com\u002Fdragonfly-xyz\u002Fuseful-solidity-patterns\u002Ftree\u002Fmain\u002Fpatterns\u002Fpermit2)\n","# Swap Integration\n\nIntegrate Uniswap swaps into frontends, backends, and smart contracts.\n\n## Prerequisites\n\nThis skill assumes familiarity with viem basics (client setup, account management, contract interactions, transaction signing). Install the **uniswap-viem** plugin for comprehensive viem\u002Fwagmi guidance: `claude plugin add @uniswap\u002Funiswap-viem`\n\n## Quick Decision Guide\n\n| Building...                    | Use This Method               |\n| ------------------------------ | ----------------------------- |\n| Frontend with React\u002FNext.js    | Trading API                   |\n| Backend script or bot          | Trading API                   |\n| Smart contract integration     | Universal Router direct calls |\n| Need full control over routing | Universal Router SDK          |\n\n### Routing Types Quick Reference\n\n| Type     | Description                             | Chains                             |\n| -------- | --------------------------------------- | ---------------------------------- |\n| CLASSIC  | Standard AMM swap through Uniswap pools | All supported chains               |\n| DUTCH_V2 | UniswapX Dutch auction V2               | Ethereum, Arbitrum, Base, Unichain |\n| PRIORITY | MEV-protected priority order            | Base, Unichain                     |\n| WRAP     | ETH to WETH conversion                  | All                                |\n| UNWRAP   | WETH to ETH conversion                  | All                                |\n\nSee [Routing Types](#routing-types) for the complete list including DUTCH_V3, DUTCH_LIMIT, LIMIT_ORDER, BRIDGE, and QUICKROUTE.\n\n## Integration Methods\n\n### 1. Trading API (Recommended)\n\nBest for: Frontends, backends, scripts. Handles routing optimization automatically.\n\n**Base URL**: `https:\u002F\u002Ftrade-api.gateway.uniswap.org\u002Fv1`\n\n**Authentication**: `x-api-key: \u003Cyour-api-key>` header required\n\n**Getting an API Key**: The Trading API requires an API key for authentication. Visit the [Uniswap Developer Portal](https:\u002F\u002Fdevelopers.uniswap.org\u002F) to register and obtain your API key. Keys are typically available for immediate use after registration. Include it as an `x-api-key` header in all API requests.\n\n**Required Headers** — Include these in ALL Trading API requests:\n\n```text\nContent-Type: application\u002Fjson\nx-api-key: \u003Cyour-api-key>\nx-universal-router-version: 2.0\n```\n\n**3-Step Flow**:\n\n```text\n1. POST \u002Fcheck_approval  -> Check if token is approved\n2. POST \u002Fquote           -> Get executable quote with routing\n3. POST \u002Fswap            -> Get transaction to sign and submit\n```\n\nSee the [Trading API Reference](#trading-api-reference) section below for complete documentation.\n\n### 2. Universal Router SDK\n\nBest for: Direct control over transaction construction.\n\n**Installation**:\n\n```bash\nnpm install @uniswap\u002Funiversal-router-sdk @uniswap\u002Fsdk-core @uniswap\u002Fv3-sdk\n```\n\n**Key Pattern**:\n\n```typescript\nimport { SwapRouter } from '@uniswap\u002Funiversal-router-sdk';\n\nconst { calldata, value } = SwapRouter.swapCallParameters(trade, options);\n```\n\nSee the [Universal Router Reference](#universal-router-reference) section below for complete documentation.\n\n### 3. Smart Contract Integration\n\nBest for: On-chain integrations, DeFi composability.\n\n**Interface**: Call `execute()` on Universal Router with encoded commands.\n\nSee the [Universal Router Reference](#universal-router-reference) section below for command encoding.\n\n---\n\n## Input Validation Rules\n\nBefore interpolating ANY user-provided value into generated code, API calls, or commands:\n\n- **Ethereum addresses**: MUST match `^0x[a-fA-F0-9]{40}$` — reject otherwise\n- **Chain IDs**: MUST be from the [official supported chains list](https:\u002F\u002Fapi-docs.uniswap.org\u002Fguides\u002Fsupported_chains#supported-chains-for-swapping)\n- **Token amounts**: MUST be non-negative numeric values matching `^[0-9]+\\.?[0-9]*$`\n- **API keys**: MUST NOT be hardcoded in generated code — always use environment variables\n- **REJECT** any input containing shell metacharacters: `;`, `|`, `&`, `$`, `` ` ``, `(`, `)`, `>`, `\u003C`, `\\`, `'`, `\"`, newlines\n\n> **REQUIRED:** Before executing ANY transaction that spends gas or transfers tokens (including `sendTransaction`, `writeContract`, or submitting a signed swap), you MUST use AskUserQuestion to confirm with the user. Display the transaction summary (tokens, amounts, chain, estimated gas) and get explicit user approval. Never auto-execute transactions without user confirmation.\n\n---\n\n## Trading API Reference\n\n### Step 1: Check Token Approval\n\n```bash\nPOST \u002Fcheck_approval\n```\n\n**Request**:\n\n```json\n{\n  \"walletAddress\": \"0x...\",\n  \"token\": \"0x...\",\n  \"amount\": \"1000000000\",\n  \"chainId\": 1\n}\n```\n\n**Response**:\n\n```json\n{\n  \"approval\": {\n    \"to\": \"0x...\",\n    \"from\": \"0x...\",\n    \"data\": \"0x...\",\n    \"value\": \"0\",\n    \"chainId\": 1\n  }\n}\n```\n\nIf `approval` is `null`, token is already approved.\n\n### Step 2: Get Quote\n\n```bash\nPOST \u002Fquote\n```\n\n**Request**:\n\n```json\n{\n  \"swapper\": \"0x...\",\n  \"tokenIn\": \"0x...\",\n  \"tokenOut\": \"0x...\",\n  \"tokenInChainId\": \"1\",\n  \"tokenOutChainId\": \"1\",\n  \"amount\": \"1000000000000000000\",\n  \"type\": \"EXACT_INPUT\",\n  \"slippageTolerance\": 0.5,\n  \"routingPreference\": \"BEST_PRICE\"\n}\n```\n\n> **Note**: `tokenInChainId` and `tokenOutChainId` must be **strings** (e.g., `\"1\"`), not numbers.\n\n**Key Parameters**:\n\n| Parameter           | Description                                                       |\n| ------------------- | ----------------------------------------------------------------- |\n| `type`              | `EXACT_INPUT` or `EXACT_OUTPUT`                                   |\n| `slippageTolerance` | 0-100 percentage                                                  |\n| `protocols`         | Optional: `[\"V2\", \"V3\", \"V4\"]`                                    |\n| `routingPreference` | `BEST_PRICE`, `FASTEST`, `CLASSIC`                                |\n| `autoSlippage`      | `true` to auto-calculate slippage (overrides `slippageTolerance`) |\n| `urgency`           | `normal` or `fast` — affects UniswapX auction timing              |\n\n**Response** — the shape differs by routing type. `BEST_PRICE` routing on Ethereum mainnet typically returns UniswapX (DUTCH_V2), not CLASSIC.\n\n**CLASSIC response**:\n\n```json\n{\n  \"routing\": \"CLASSIC\",\n  \"quote\": {\n    \"input\": { \"token\": \"0x...\", \"amount\": \"1000000000000000000\" },\n    \"output\": { \"token\": \"0x...\", \"amount\": \"999000000\" },\n    \"slippage\": 0.5,\n    \"route\": [],\n    \"gasFee\": \"5000000000000000\",\n    \"gasFeeUSD\": \"0.01\",\n    \"gasUseEstimate\": \"150000\"\n  },\n  \"permitData\": null\n}\n```\n\n**UniswapX (DUTCH_V2\u002FV3\u002FPRIORITY) response** — different `quote` shape, no `quote.output`:\n\n```json\n{\n  \"routing\": \"DUTCH_V2\",\n  \"quote\": {\n    \"orderInfo\": {\n      \"reactor\": \"0x...\",\n      \"swapper\": \"0x...\",\n      \"nonce\": \"...\",\n      \"deadline\": 1772031054,\n      \"cosigner\": \"0x...\",\n      \"input\": {\n        \"token\": \"0x...\",\n        \"startAmount\": \"1000000000000000000\",\n        \"endAmount\": \"1000000000000000000\"\n      },\n      \"outputs\": [\n        {\n          \"token\": \"0x...\",\n          \"startAmount\": \"999000000\",\n          \"endAmount\": \"994000000\",\n          \"recipient\": \"0x...\"\n        }\n      ],\n      \"chainId\": 1\n    },\n    \"encodedOrder\": \"0x...\",\n    \"orderHash\": \"0x...\"\n  },\n  \"permitData\": { \"domain\": {}, \"types\": {}, \"values\": {} }\n}\n```\n\n> **UniswapX output amount**: Use `quote.orderInfo.outputs[0].startAmount` for the best-case fill amount. The `endAmount` is the floor after full auction decay. There is no `quote.output.amount` on UniswapX responses — accessing it will throw at runtime.\n>\n> **Display tip**: For CLASSIC routes, use `gasFeeUSD` (a string with the USD value) for gas cost display. Do **not** manually convert `gasFee` (wei) using a hardcoded ETH price — this leads to wildly inaccurate estimates (e.g., ~$87 instead of ~$0.01). UniswapX routes are gasless for the swapper.\n\nSee [QuoteResponse TypeScript Types](#7-quoteresponse-typescript-types) for compile-time type safety across routing types.\n\n### Step 3: Execute Swap\n\n```bash\nPOST \u002Fswap\n```\n\n**Request** - Spread the quote response directly into the body:\n\n```typescript\n\u002F\u002F CORRECT: Spread the quote response, strip null fields\nconst quoteResponse = await fetchQuote(params);\n\n\u002F\u002F Always strip permitData\u002FpermitTransaction — handle them explicitly by routing type\nconst { permitData, permitTransaction, ...cleanQuote } = quoteResponse;\nconst swapRequest: Record\u003Cstring, unknown> = { ...cleanQuote };\n\nconst isUniswapX =\n  quoteResponse.routing === 'DUTCH_V2' ||\n  quoteResponse.routing === 'DUTCH_V3' ||\n  quoteResponse.routing === 'PRIORITY';\n\nif (isUniswapX) {\n  \u002F\u002F UniswapX: signature only — permitData must NOT go to \u002Fswap\n  if (permit2Signature) swapRequest.signature = permit2Signature;\n} else {\n  \u002F\u002F CLASSIC: both signature and permitData, or neither\n  if (permit2Signature && permitData && typeof permitData === 'object') {\n    swapRequest.signature = permit2Signature;\n    swapRequest.permitData = permitData;\n  }\n}\n```\n\n**Critical**: Do NOT wrap the quote in `{quote: quoteResponse}`. The API expects the quote response fields spread into the request body.\n\n**Permit2 Rules** (CLASSIC routes):\n\n- `signature` and `permitData` must BOTH be present, or BOTH be absent\n- Never set `permitData: null` — omit the field entirely\n- The quote response often includes `permitData: null` — strip this before sending\n\n**UniswapX Routes** (DUTCH_V2\u002FV3\u002FPRIORITY): `permitData` is used locally to sign the order but must be **excluded** from the `\u002Fswap` body. See [Signing vs. Submission Flow](#uniswapx-signing-vs-submission-flow).\n\n**Response** (ready-to-sign transaction):\n\n```json\n{\n  \"swap\": {\n    \"to\": \"0x...\",\n    \"from\": \"0x...\",\n    \"data\": \"0x...\",\n    \"value\": \"0\",\n    \"chainId\": 1,\n    \"gasLimit\": \"250000\"\n  }\n}\n```\n\n**Response Validation** - Always validate before broadcasting:\n\n```typescript\nfunction validateSwapResponse(response: SwapResponse): void {\n  if (!response.swap?.data || response.swap.data === '' || response.swap.data === '0x') {\n    throw new Error('swap.data is empty - quote may have expired');\n  }\n  if (!isAddress(response.swap.to) || !isAddress(response.swap.from)) {\n    throw new Error('Invalid address in swap response');\n  }\n}\n```\n\n### Supported Chains\n\nSee the [official supported chains list](https:\u002F\u002Fapi-docs.uniswap.org\u002Fguides\u002Fsupported_chains#supported-chains-for-swapping) for the current set of chains and their IDs.\n\n### Routing Types\n\n| Type        | Description                                   |\n| ----------- | --------------------------------------------- |\n| CLASSIC     | Standard AMM swap through Uniswap pools       |\n| DUTCH_V2    | UniswapX Dutch auction V2                     |\n| DUTCH_V3    | UniswapX Dutch auction V3                     |\n| PRIORITY    | MEV-protected priority order (Base, Unichain) |\n| DUTCH_LIMIT | UniswapX Dutch limit order                    |\n| LIMIT_ORDER | Limit order                                   |\n| WRAP        | ETH to WETH conversion                        |\n| UNWRAP      | WETH to ETH conversion                        |\n| BRIDGE      | Cross-chain bridge                            |\n| QUICKROUTE  | Fast approximation quote                      |\n\n**UniswapX availability**: UniswapX V2 orders are supported on Ethereum (1), Arbitrum (42161), Base (8453), and Unichain (130). The auction mechanism varies by chain — see [UniswapX Auction Types](#uniswapx-auction-types) below.\n\n---\n\n## Critical Implementation Notes\n\nThese are common pitfalls discovered during real-world Trading API integration. **Follow these rules to avoid on-chain reverts and API errors.**\n\n### 1. Swap Request Body Format\n\nThe `\u002Fswap` endpoint expects the quote response **spread into the request body**, not wrapped in a `quote` field.\n\n```typescript\n\u002F\u002F WRONG - causes \"quote does not match any of the allowed types\"\nconst badRequest = {\n  quote: quoteResponse, \u002F\u002F Don't wrap!\n  signature: '0x...',\n};\n\n\u002F\u002F CORRECT - spread the quote response\nconst goodRequest = {\n  ...quoteResponse,\n  signature: '0x...', \u002F\u002F Only if using Permit2\n};\n```\n\n### 2. Null Field Handling\n\nThe API rejects `permitData: null`. Additionally, `permitData` handling differs by routing type — see [Signing vs. Submission Flow](#uniswapx-signing-vs-submission-flow) for the full explanation.\n\n```typescript\nfunction prepareSwapRequest(quoteResponse: QuoteResponse, signature?: string): object {\n  \u002F\u002F Always strip permitData and permitTransaction from the spread — handle them explicitly\n  const { permitData, permitTransaction, ...cleanQuote } = quoteResponse;\n  const request: Record\u003Cstring, unknown> = { ...cleanQuote };\n\n  \u002F\u002F UniswapX (DUTCH_V2, DUTCH_V3, PRIORITY): permitData is for LOCAL signing only.\n  \u002F\u002F The \u002Fswap body must NOT include permitData — the order is encoded in\n  \u002F\u002F quote.encodedOrder. Only the signature is needed.\n  const isUniswapX =\n    quoteResponse.routing === 'DUTCH_V2' ||\n    quoteResponse.routing === 'DUTCH_V3' ||\n    quoteResponse.routing === 'PRIORITY';\n\n  if (isUniswapX) {\n    if (signature) request.signature = signature;\n  } else {\n    \u002F\u002F CLASSIC: both signature and permitData required together, or both omitted.\n    \u002F\u002F The Universal Router contract needs permitData to verify the Permit2\n    \u002F\u002F authorization on-chain.\n    if (signature && permitData && typeof permitData === 'object') {\n      request.signature = signature;\n      request.permitData = permitData;\n    }\n  }\n\n  return request;\n}\n```\n\n### 3. Permit2 Field Rules\n\nThe rules for `signature` and `permitData` in the `\u002Fswap` request body depend on the routing type:\n\n**CLASSIC routes**:\n\n| Scenario                   | `signature` | `permitData` |\n| -------------------------- | ----------- | ------------ |\n| Standard swap (no Permit2) | Omit        | Omit         |\n| Permit2 swap               | Required    | Required     |\n| **Invalid**                | Present     | Missing      |\n| **Invalid**                | Missing     | Present      |\n| **Invalid (API error)**    | Any         | `null`       |\n\n**UniswapX routes (DUTCH_V2\u002FV3\u002FPRIORITY)**:\n\n| Scenario       | `signature` | `permitData`             |\n| -------------- | ----------- | ------------------------ |\n| UniswapX order | Required    | **Omit** (do not send)   |\n| **Invalid**    | Any         | Present (schema rejects) |\n\n### 4. Pre-Broadcast Validation\n\nAlways validate the swap response before sending to the blockchain:\n\n```typescript\nimport { isAddress, isHex } from 'viem';\n\nfunction validateSwapBeforeBroadcast(swap: SwapTransaction): void {\n  \u002F\u002F 1. data must be non-empty hex\n  if (!swap.data || swap.data === '' || swap.data === '0x') {\n    throw new Error('swap.data is empty - this will revert on-chain. Re-fetch the quote.');\n  }\n\n  if (!isHex(swap.data)) {\n    throw new Error('swap.data is not valid hex');\n  }\n\n  \u002F\u002F 2. Addresses must be valid\n  if (!isAddress(swap.to)) {\n    throw new Error('swap.to is not a valid address');\n  }\n\n  if (!isAddress(swap.from)) {\n    throw new Error('swap.from is not a valid address');\n  }\n\n  \u002F\u002F 3. Value must be present (can be \"0\" for non-ETH swaps)\n  if (swap.value === undefined || swap.value === null) {\n    throw new Error('swap.value is missing');\n  }\n}\n```\n\n### 5. Browser Environment Setup\n\nWhen using viem\u002Fwagmi in browser environments, you need Node.js polyfills:\n\n**Install buffer polyfill**:\n\n```bash\nnpm install buffer\n```\n\n**Add to your entry file (before other imports)**:\n\n```typescript\n\u002F\u002F src\u002Fmain.tsx or src\u002Findex.tsx\nimport { Buffer } from 'buffer';\nglobalThis.Buffer = Buffer;\n\n\u002F\u002F Then your other imports\nimport React from 'react';\nimport { WagmiProvider } from 'wagmi';\n\u002F\u002F ...\n```\n\n**Vite configuration** (`vite.config.ts`):\n\n```typescript\nexport default defineConfig({\n  define: {\n    global: 'globalThis',\n  },\n  optimizeDeps: {\n    include: ['buffer'],\n  },\n  resolve: {\n    alias: {\n      buffer: 'buffer',\n    },\n  },\n});\n```\n\nWithout this setup, you'll see: `ReferenceError: Buffer is not defined`\n\n#### CORS Proxy Configuration\n\nThe Trading API does not support browser CORS preflight requests — `OPTIONS` requests return `415 Unsupported Media Type`. Direct `fetch()` calls from a browser will always fail. You **must** proxy API requests through your own server or dev server.\n\n**Vite dev proxy** (merge into the same `vite.config.ts` used for the Buffer polyfill above):\n\n```typescript\nexport default defineConfig({\n  server: {\n    proxy: {\n      '\u002Fapi\u002Funiswap': {\n        target: 'https:\u002F\u002Ftrade-api.gateway.uniswap.org\u002Fv1',\n        changeOrigin: true,\n        rewrite: (path) => path.replace(\u002F^\\\u002Fapi\\\u002Funiswap\u002F, ''),\n      },\n    },\n  },\n});\n```\n\nThen use `\u002Fapi\u002Funiswap\u002Fquote` instead of the full URL in your frontend code.\n\n**Vercel production proxy** (`vercel.json`):\n\n```json\n{\n  \"rewrites\": [\n    {\n      \"source\": \"\u002Fapi\u002Funiswap\u002F:path*\",\n      \"destination\": \"https:\u002F\u002Ftrade-api.gateway.uniswap.org\u002Fv1\u002F:path*\"\n    }\n  ]\n}\n```\n\n**Cloudflare Pages** (`public\u002F_redirects`):\n\n```text\n\u002Fapi\u002Funiswap\u002F* https:\u002F\u002Ftrade-api.gateway.uniswap.org\u002Fv1\u002F:splat 200\n```\n\n**Next.js** (`next.config.js`):\n\n```javascript\nmodule.exports = {\n  async rewrites() {\n    return [\n      {\n        source: '\u002Fapi\u002Funiswap\u002F:path*',\n        destination: 'https:\u002F\u002Ftrade-api.gateway.uniswap.org\u002Fv1\u002F:path*',\n      },\n    ];\n  },\n};\n```\n\nWithout a proxy, you'll see: `415 Unsupported Media Type` on preflight or CORS errors in the browser console.\n\n### 6. Quote Freshness\n\n- Quotes expire quickly (typically 30 seconds)\n- Always re-fetch if the user takes time to review\n- Use the `deadline` parameter to prevent stale execution\n- If `\u002Fswap` returns empty `data`, the quote likely expired\n\n### 7. QuoteResponse TypeScript Types\n\nThe quote response shape differs by routing type. Use a discriminated union on the `routing` field to get compile-time safety instead of casting to `any`:\n\n```typescript\ntype ClassicQuoteResponse = {\n  routing: 'CLASSIC' | 'WRAP' | 'UNWRAP';\n  quote: {\n    input: { token: string; amount: string };\n    output: { token: string; amount: string };\n    slippage: number;\n    route: unknown[];\n    gasFee: string;\n    gasFeeUSD: string;\n    gasUseEstimate: string;\n  };\n  permitData: Record\u003Cstring, unknown> | null;\n};\n\ntype DutchOrderOutput = {\n  token: string;\n  startAmount: string;\n  endAmount: string;\n  recipient: string;\n};\n\ntype UniswapXQuoteResponse = {\n  routing: 'DUTCH_V2' | 'DUTCH_V3' | 'PRIORITY';\n  quote: {\n    orderInfo: {\n      outputs: DutchOrderOutput[];\n      input: { token: string; startAmount: string; endAmount: string };\n      deadline: number;\n      nonce: string;\n    };\n    encodedOrder: string;\n    orderHash: string;\n  };\n  \u002F\u002F EIP-712 typed data — sign locally, do NOT send to \u002Fswap\n  permitData: Record\u003Cstring, unknown> | null;\n};\n\ntype QuoteResponse = ClassicQuoteResponse | UniswapXQuoteResponse;\n\n\u002F\u002F Type guard for routing-aware logic\nfunction isUniswapXQuote(q: QuoteResponse): q is UniswapXQuoteResponse {\n  return q.routing === 'DUTCH_V2' || q.routing === 'DUTCH_V3' || q.routing === 'PRIORITY';\n}\n\n\u002F\u002F Reading the output amount by routing type\nfunction getOutputAmount(q: QuoteResponse): string {\n  if (isUniswapXQuote(q)) {\n    const firstOutput = q.quote.orderInfo.outputs[0];\n    if (!firstOutput) throw new Error('UniswapX quote has no outputs');\n    \u002F\u002F startAmount = best-case fill; endAmount = floor after auction decay\n    return firstOutput.startAmount;\n  }\n  return q.quote.output.amount;\n}\n```\n\n---\n\n## Universal Router Reference\n\nThe Universal Router is a unified interface for swapping across Uniswap v2, v3, and v4.\n\n### Core Function\n\n```solidity\nfunction execute(\n    bytes calldata commands,\n    bytes[] calldata inputs,\n    uint256 deadline\n) external payable;\n```\n\n### Command Encoding\n\nEach command is a single byte:\n\n| Bits | Name     | Purpose                             |\n| ---- | -------- | ----------------------------------- |\n| 0    | flag     | Allow revert (1 = continue on fail) |\n| 1-2  | reserved | Use 0                               |\n| 3-7  | command  | Operation identifier                |\n\n### Swap Commands\n\n| Code | Command           | Description               |\n| ---- | ----------------- | ------------------------- |\n| 0x00 | V3_SWAP_EXACT_IN  | v3 swap with exact input  |\n| 0x01 | V3_SWAP_EXACT_OUT | v3 swap with exact output |\n| 0x08 | V2_SWAP_EXACT_IN  | v2 swap with exact input  |\n| 0x09 | V2_SWAP_EXACT_OUT | v2 swap with exact output |\n| 0x10 | V4_SWAP           | v4 swap                   |\n\n### Token Operations\n\n| Code | Command     | Description                |\n| ---- | ----------- | -------------------------- |\n| 0x04 | SWEEP       | Clear router token balance |\n| 0x05 | TRANSFER    | Send specific amount       |\n| 0x0b | WRAP_ETH    | ETH to WETH                |\n| 0x0c | UNWRAP_WETH | WETH to ETH                |\n\n### Permit2 Commands\n\n| Code | Command               | Description           |\n| ---- | --------------------- | --------------------- |\n| 0x02 | PERMIT2_TRANSFER_FROM | Single token transfer |\n| 0x03 | PERMIT2_PERMIT_BATCH  | Batch approval        |\n| 0x0a | PERMIT2_PERMIT        | Single approval       |\n\n### SDK Usage\n\n```typescript\nimport { SwapRouter, UniswapTrade } from '@uniswap\u002Funiversal-router-sdk'\nimport { TradeType } from '@uniswap\u002Fsdk-core'\n\n\u002F\u002F Build trade using v3-sdk or router-sdk\nconst trade = new RouterTrade({\n  v3Routes: [...],\n  tradeType: TradeType.EXACT_INPUT\n})\n\n\u002F\u002F Get calldata for Universal Router\nconst { calldata, value } = SwapRouter.swapCallParameters(trade, {\n  slippageTolerance: new Percent(50, 10000), \u002F\u002F 0.5%\n  recipient: walletAddress,\n  deadline: Math.floor(Date.now() \u002F 1000) + 1200 \u002F\u002F 20 min\n})\n\n\u002F\u002F Send transaction\nconst tx = await wallet.sendTransaction({\n  to: UNIVERSAL_ROUTER_ADDRESS,\n  data: calldata,\n  value\n})\n```\n\n---\n\n## Permit2 Integration\n\nPermit2 enables signature-based token approvals instead of on-chain approve() calls.\n\n### Approval Target: Permit2 vs Legacy (Direct to Router)\n\nThere are two approval paths. Choose based on your integration type:\n\n| Approach                    | Approve To       | Per-Swap Auth       | Best For                         |\n| --------------------------- | ---------------- | ------------------- | -------------------------------- |\n| **Permit2** (recommended)   | Permit2 contract | EIP-712 signature   | Frontends with user interaction  |\n| **Legacy** (direct approve) | Universal Router | None (pre-approved) | Backend services, smart accounts |\n\n**Permit2 flow** (frontend with user signing):\n\n1. User approves token to Permit2 contract (one-time)\n2. Each swap: user signs an EIP-712 permit message\n3. Universal Router uses the signature to transfer tokens via Permit2\n\n**Legacy flow** (backend services, ERC-4337 smart accounts):\n\n1. Approve token directly to the Universal Router address (one-time)\n2. Each swap: no additional authorization needed\n3. Simpler for automated systems that cannot sign EIP-712 messages\n\nUse the Trading API's `\u002Fcheck_approval` endpoint — it returns the correct approval target based on the routing type.\n\n### How It Works\n\n1. User approves Permit2 contract once (infinite approval)\n2. For each swap, user signs a message authorizing the transfer\n3. Universal Router uses signature to transfer tokens via Permit2\n\n### Two Modes\n\n| Mode              | Description                                |\n| ----------------- | ------------------------------------------ |\n| SignatureTransfer | One-time signature, no on-chain state      |\n| AllowanceTransfer | Time-limited allowance with on-chain state |\n\n### Integration Pattern\n\n```typescript\nimport { getContract, maxUint256, type Address } from 'viem';\n\nconst PERMIT2_ADDRESS = '0x000000000022D473030F116dDEE9F6B43aC78BA3' as const;\n\n\u002F\u002F Check if Permit2 approval exists\nconst allowance = await publicClient.readContract({\n  address: PERMIT2_ADDRESS,\n  abi: permit2Abi,\n  functionName: 'allowance',\n  args: [userAddress, tokenAddress, spenderAddress],\n});\n\n\u002F\u002F If not approved, user must approve Permit2 first\nif (allowance.amount \u003C requiredAmount) {\n  const hash = await walletClient.writeContract({\n    address: tokenAddress,\n    abi: erc20Abi,\n    functionName: 'approve',\n    args: [PERMIT2_ADDRESS, maxUint256],\n  });\n  await publicClient.waitForTransactionReceipt({ hash });\n}\n\n\u002F\u002F Then sign permit for the swap\nconst permitSignature = await signPermit(...);\n```\n\n---\n\n## UniswapX Auction Types\n\nUniswapX routes swaps through off-chain fillers who compete to execute orders at better prices than on-chain AMMs. The auction mechanism varies by chain.\n\n### Exclusive Dutch Auction (Ethereum)\n\n- Starts with an RFQ (Request for Quote) phase where permissioned quoters compete\n- Winning quoter receives **exclusive filling rights** for a set period\n- If the exclusive filler doesn't execute, falls back to an open Dutch auction where the price decays each block\n- Best for large swaps where MEV protection matters most\n\n**Trading API routing type**: `DUTCH_V2` or `DUTCH_V3`\n\n### Open Dutch Auction (Arbitrum)\n\n- Direct open auction without an RFQ phase\n- Fillers compete on-chain through a descending price mechanism\n- Leverages Arbitrum's fast 0.25-second block times for rapid price discovery\n- The **Unimind algorithm** sets auction parameters based on historical pair performance\n\n**Trading API routing type**: `DUTCH_V2`\n\n### Priority Gas Auction (Base, Unichain)\n\n- Fillers bid by submitting transactions with varying **priority fees** at a target block\n- Highest priority fee wins the right to fill the order\n- Exploits OP Stack's priority ordering mechanism\n- Effective on chains where block builders respect priority ordering\n\n**Trading API routing type**: `PRIORITY`\n\n### Key Properties (All Auction Types)\n\n- **Gasless for users** — fillers pay gas fees, incorporated into final pricing\n- **No cost on failure** — if a swap doesn't fill, the user pays nothing\n- **MEV protection** — auction mechanics prevent frontrunning and sandwich attacks\n- UniswapX V2 is currently supported on Ethereum (1), Arbitrum (42161), Base (8453), and Unichain (130)\n\nFor more detail, see the [UniswapX Auction Types documentation](https:\u002F\u002Fdocs.uniswap.org\u002Fcontracts\u002Funiswapx\u002Fauctiontypes).\n\n### UniswapX: Signing vs. Submission Flow\n\nThe `permitData` field in the quote response serves different purposes depending on the routing type. Conflating the two causes `RequestValidationError` on `\u002Fswap`.\n\n**CLASSIC flow** — `permitData` goes to the server:\n\n1. `\u002Fquote` returns `permitData` (EIP-712 typed data for the Permit2 allowance)\n2. User signs `permitData` locally → produces `signature`\n3. `\u002Fswap` body includes **both** `signature` and `permitData` — the Universal Router contract needs `permitData` to reconstruct and verify the Permit2 authorization on-chain\n\n**UniswapX flow (DUTCH_V2\u002FV3\u002FPRIORITY)** — `permitData` stays local:\n\n1. `\u002Fquote` returns `permitData` (EIP-712 typed data for the Dutch order)\n2. User signs `permitData` locally → produces `signature`\n3. `\u002Fswap` body includes **only** `signature` — the order is already fully encoded in `quote.encodedOrder`, which the off-chain filler system reads directly. Sending `permitData` to `\u002Fswap` causes a schema validation error.\n\n| Route Type           | Sign with `permitData`? | Send `permitData` to `\u002Fswap`? | Send `signature` to `\u002Fswap`? |\n| -------------------- | ----------------------- | ----------------------------- | ---------------------------- |\n| CLASSIC              | Yes                     | **Yes** (router needs it)     | Yes (if using Permit2)       |\n| DUTCH_V2\u002FV3\u002FPRIORITY | Yes                     | **No** (schema rejects it)    | Yes                          |\n\n> **Common mistake**: The API error `\"quote\" does not match any of the allowed types` often points at the `quote` field, but the actual cause is `permitData` being present for a UniswapX route. Strip `permitData` before submitting — see the routing-aware `prepareSwapRequest` in [Null Field Handling](#2-null-field-handling).\n\n---\n\n## Direct Universal Router Integration (SDK)\n\nFor direct Universal Router integration without the Trading API, use the SDK's high-level API.\n\n### Installation\n\n```bash\nnpm install @uniswap\u002Funiversal-router-sdk @uniswap\u002Frouter-sdk @uniswap\u002Fsdk-core @uniswap\u002Fv3-sdk viem\n```\n\n### High-Level Approach (Recommended)\n\nUse `RouterTrade` + `SwapRouter.swapCallParameters()` for automatic command building:\n\n```typescript\nimport { SwapRouter } from '@uniswap\u002Funiversal-router-sdk';\nimport { Trade as RouterTrade } from '@uniswap\u002Frouter-sdk';\nimport { TradeType, Percent } from '@uniswap\u002Fsdk-core';\nimport { Route as V3Route, Pool } from '@uniswap\u002Fv3-sdk';\n\n\u002F\u002F 1. Fetch pool data (required to construct routes)\n\u002F\u002F Using viem to read on-chain pool state:\nconst slot0 = await publicClient.readContract({\n  address: poolAddress,\n  abi: [\n    {\n      name: 'slot0',\n      type: 'function',\n      stateMutability: 'view',\n      inputs: [],\n      outputs: [\n        { name: 'sqrtPriceX96', type: 'uint160' },\n        { name: 'tick', type: 'int24' },\n        { name: 'observationIndex', type: 'uint16' },\n        { name: 'observationCardinality', type: 'uint16' },\n        { name: 'observationCardinalityNext', type: 'uint16' },\n        { name: 'feeProtocol', type: 'uint8' },\n        { name: 'unlocked', type: 'bool' },\n      ],\n    },\n  ],\n  functionName: 'slot0',\n});\nconst liquidity = await publicClient.readContract({\n  address: poolAddress,\n  abi: [\n    {\n      name: 'liquidity',\n      type: 'function',\n      stateMutability: 'view',\n      inputs: [],\n      outputs: [{ type: 'uint128' }],\n    },\n  ],\n  functionName: 'liquidity',\n});\n\nconst pool = new Pool(tokenIn, tokenOut, fee, slot0[0].toString(), liquidity.toString(), slot0[1]);\n\n\u002F\u002F 2. Build route and trade\nconst route = new V3Route([pool], tokenIn, tokenOut);\nconst trade = RouterTrade.createUncheckedTrade({\n  route,\n  inputAmount: amountIn,\n  outputAmount: expectedOut,\n  tradeType: TradeType.EXACT_INPUT,\n});\n\n\u002F\u002F 3. Get calldata\nconst { calldata, value } = SwapRouter.swapCallParameters(trade, {\n  slippageTolerance: new Percent(50, 10000), \u002F\u002F 0.5%\n  recipient: walletAddress,\n  deadline: Math.floor(Date.now() \u002F 1000) + 1800,\n});\n\n\u002F\u002F 4. Execute with viem\nconst hash = await walletClient.sendTransaction({\n  to: UNIVERSAL_ROUTER_ADDRESS,\n  data: calldata,\n  value: BigInt(value),\n});\n```\n\n### Low-Level Approach (Manual Commands)\n\nFor custom flows (fee collection, complex routing), use `RoutePlanner` directly:\n\n```typescript\nimport { RoutePlanner, CommandType, ROUTER_AS_RECIPIENT } from '@uniswap\u002Funiversal-router-sdk';\nimport { encodeRouteToPath } from '@uniswap\u002Fv3-sdk';\n\n\u002F\u002F Special addresses\nconst MSG_SENDER = '0x0000000000000000000000000000000000000001';\nconst ADDRESS_THIS = '0x0000000000000000000000000000000000000002';\n```\n\n### Example: V3 Swap with Manual Commands\n\n```typescript\nimport { RoutePlanner, CommandType } from '@uniswap\u002Funiversal-router-sdk';\nimport { encodeRouteToPath, Route } from '@uniswap\u002Fv3-sdk';\n\nasync function swapV3Manual(route: Route, amountIn: bigint, amountOutMin: bigint) {\n  const planner = new RoutePlanner();\n\n  \u002F\u002F Encode V3 path from route\n  const path = encodeRouteToPath(route, false); \u002F\u002F false = exactInput\n\n  planner.addCommand(CommandType.V3_SWAP_EXACT_IN, [\n    MSG_SENDER, \u002F\u002F recipient\n    amountIn, \u002F\u002F amountIn\n    amountOutMin, \u002F\u002F amountOutMin\n    path, \u002F\u002F encoded path\n    true, \u002F\u002F payerIsUser\n  ]);\n\n  return executeRoute(planner);\n}\n```\n\n### Example: ETH to Token (Wrap + Swap)\n\n```typescript\nasync function swapEthToToken(route: Route, amountIn: bigint, amountOutMin: bigint) {\n  const planner = new RoutePlanner();\n  const path = encodeRouteToPath(route, false);\n\n  \u002F\u002F 1. Wrap ETH to WETH (keep in router)\n  planner.addCommand(CommandType.WRAP_ETH, [ADDRESS_THIS, amountIn]);\n\n  \u002F\u002F 2. Swap WETH → Token (payerIsUser = false since using router's WETH)\n  planner.addCommand(CommandType.V3_SWAP_EXACT_IN, [\n    MSG_SENDER,\n    amountIn,\n    amountOutMin,\n    path,\n    false,\n  ]);\n\n  return executeRoute(planner, { value: amountIn });\n}\n```\n\n### Example: Token to ETH (Swap + Unwrap)\n\n```typescript\nasync function swapTokenToEth(route: Route, amountIn: bigint, amountOutMin: bigint) {\n  const planner = new RoutePlanner();\n  const path = encodeRouteToPath(route, false);\n\n  \u002F\u002F 1. Swap Token → WETH (output to router)\n  planner.addCommand(CommandType.V3_SWAP_EXACT_IN, [\n    ADDRESS_THIS,\n    amountIn,\n    amountOutMin,\n    path,\n    true,\n  ]);\n\n  \u002F\u002F 2. Unwrap WETH to ETH\n  planner.addCommand(CommandType.UNWRAP_WETH, [MSG_SENDER, amountOutMin]);\n\n  return executeRoute(planner);\n}\n```\n\n### Example: Fee Collection with PAY_PORTION\n\n```typescript\nasync function swapWithFee(route: Route, amountIn: bigint, feeRecipient: Address, feeBips: number) {\n  const planner = new RoutePlanner();\n  const path = encodeRouteToPath(route, false);\n  const outputToken = route.output.wrapped.address;\n\n  \u002F\u002F Swap to router (ADDRESS_THIS)\n  planner.addCommand(CommandType.V3_SWAP_EXACT_IN, [ADDRESS_THIS, amountIn, 0n, path, true]);\n\n  \u002F\u002F Pay fee portion (e.g., 30 bips = 0.3%)\n  planner.addCommand(CommandType.PAY_PORTION, [outputToken, feeRecipient, feeBips]);\n\n  \u002F\u002F Sweep remainder to user\n  planner.addCommand(CommandType.SWEEP, [outputToken, MSG_SENDER, 0n]);\n\n  return executeRoute(planner);\n}\n```\n\n### Execute Route Helper\n\n```typescript\nimport { UNIVERSAL_ROUTER_ADDRESS } from '@uniswap\u002Funiversal-router-sdk';\n\nconst ROUTER_ABI = [\n  {\n    name: 'execute',\n    type: 'function',\n    stateMutability: 'payable',\n    inputs: [\n      { name: 'commands', type: 'bytes' },\n      { name: 'inputs', type: 'bytes[]' },\n      { name: 'deadline', type: 'uint256' },\n    ],\n    outputs: [],\n  },\n] as const;\n\nasync function executeRoute(planner: RoutePlanner, options?: { value?: bigint }) {\n  const deadline = BigInt(Math.floor(Date.now() \u002F 1000) + 1800);\n  const routerAddress = UNIVERSAL_ROUTER_ADDRESS('2.0', 1); \u002F\u002F version, chainId\n\n  const { request } = await publicClient.simulateContract({\n    address: routerAddress,\n    abi: ROUTER_ABI,\n    functionName: 'execute',\n    args: [planner.commands, planner.inputs, deadline],\n    account,\n    value: options?.value ?? 0n,\n  });\n\n  return walletClient.writeContract(request);\n}\n```\n\n### Command Cheat Sheet\n\n| Command           | Parameters                                               |\n| ----------------- | -------------------------------------------------------- |\n| V3_SWAP_EXACT_IN  | (recipient, amountIn, amountOutMin, path, payerIsUser)   |\n| V3_SWAP_EXACT_OUT | (recipient, amountOut, amountInMax, path, payerIsUser)   |\n| V2_SWAP_EXACT_IN  | (recipient, amountIn, amountOutMin, path[], payerIsUser) |\n| V2_SWAP_EXACT_OUT | (recipient, amountOut, amountInMax, path[], payerIsUser) |\n| WRAP_ETH          | (recipient, amount)                                      |\n| UNWRAP_WETH       | (recipient, amountMin)                                   |\n| SWEEP             | (token, recipient, amountMin)                            |\n| TRANSFER          | (token, recipient, amount)                               |\n| PAY_PORTION       | (token, recipient, bips)                                 |\n\n### Fee Tiers\n\n| Tier   | Value | Percentage |\n| ------ | ----- | ---------- |\n| LOWEST | 100   | 0.01%      |\n| LOW    | 500   | 0.05%      |\n| MEDIUM | 3000  | 0.30%      |\n| HIGH   | 10000 | 1.00%      |\n\n---\n\n## Common Integration Patterns\n\n### Frontend Swap Hook (React)\n\n**Note**: Ensure you've set up the Buffer polyfill and CORS proxy (see Critical Implementation Notes). For wagmi v2 `useWalletClient()` pitfalls, see [wagmi v2 Integration Pitfalls](#wagmi-v2-integration-pitfalls) below.\n\n```typescript\nimport { isAddress, isHex } from 'viem';\nimport { useWalletClient } from 'wagmi';\n\n\u002F\u002F In browser apps, use your CORS proxy path instead (see CORS Proxy Configuration)\n\u002F\u002F e.g., const API_URL = '\u002Fapi\u002Funiswap';\nconst API_URL = 'https:\u002F\u002Ftrade-api.gateway.uniswap.org\u002Fv1';\n\nfunction useSwap() {\n  const { data: walletClient } = useWalletClient();\n  const [quoteResponse, setQuoteResponse] = useState(null);\n  const [loading, setLoading] = useState(false);\n  const [error, setError] = useState(null);\n\n  const getQuote = async (params) => {\n    setLoading(true);\n    setError(null);\n    try {\n      const response = await fetch(`${API_URL}\u002Fquote`, {\n        method: 'POST',\n        headers: {\n          'Content-Type': 'application\u002Fjson',\n          'x-api-key': API_KEY,\n          'x-universal-router-version': '2.0',\n        },\n        body: JSON.stringify(params),\n      });\n      const data = await response.json();\n      if (!response.ok) throw new Error(data.detail || 'Quote failed');\n      setQuoteResponse(data); \u002F\u002F Store the FULL response, not just data.quote\n    } catch (err) {\n      setError(err.message);\n    } finally {\n      setLoading(false);\n    }\n  };\n\n  const executeSwap = async (permit2Signature?: string) => {\n    if (!quoteResponse) throw new Error('No quote available');\n\n    \u002F\u002F Strip null fields and spread quote response into body\n    const { permitData, permitTransaction, ...cleanQuote } = quoteResponse;\n    const swapRequest: Record\u003Cstring, unknown> = { ...cleanQuote };\n\n    \u002F\u002F CRITICAL: permitData handling differs by routing type\n    const isUniswapX =\n      quoteResponse.routing === 'DUTCH_V2' ||\n      quoteResponse.routing === 'DUTCH_V3' ||\n      quoteResponse.routing === 'PRIORITY';\n\n    if (isUniswapX) {\n      \u002F\u002F UniswapX: signature only — permitData must NOT be sent to \u002Fswap\n      \u002F\u002F (permitData is used locally to sign the order, not submitted to the API)\n      if (permit2Signature) swapRequest.signature = permit2Signature;\n    } else {\n      \u002F\u002F CLASSIC: both signature and permitData required together, or both omitted\n      if (permit2Signature && permitData && typeof permitData === 'object') {\n        swapRequest.signature = permit2Signature;\n        swapRequest.permitData = permitData;\n      }\n    }\n\n    const swapResponse = await fetch(`${API_URL}\u002Fswap`, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application\u002Fjson',\n        'x-api-key': API_KEY,\n        'x-universal-router-version': '2.0',\n      },\n      body: JSON.stringify(swapRequest),\n    });\n    const data = await swapResponse.json();\n    if (!swapResponse.ok) throw new Error(data.detail || 'Swap failed');\n\n    \u002F\u002F CRITICAL: Validate response before broadcasting\n    if (!data.swap?.data || data.swap.data === '' || data.swap.data === '0x') {\n      throw new Error('Empty swap data - quote may have expired. Please refresh.');\n    }\n\n    \u002F\u002F Send transaction via wallet (walletClient from useWalletClient())\n    if (!walletClient) throw new Error('Wallet not connected');\n    const tx = await walletClient.sendTransaction(data.swap);\n    return tx;\n  };\n\n  return { quote: quoteResponse?.quote, loading, error, getQuote, executeSwap };\n}\n```\n\n### wagmi v2 Integration Pitfalls\n\nThe `useWalletClient()` hook from wagmi v2 can return `undefined` even when the wallet is connected — it resolves asynchronously. This causes \"wallet not connected\" errors at swap time. Additionally, the returned client needs a `chain` for `sendTransaction()` to work.\n\n**Recommended pattern** — use `@wagmi\u002Fcore` action functions at swap time instead of hooks:\n\n```typescript\nimport { getWalletClient, getPublicClient, switchChain } from '@wagmi\u002Fcore';\nimport type { Config } from 'wagmi';\n\nasync function executeSwapTransaction(\n  config: Config,\n  chainId: number,\n  swapTx: { to: string; data: string; value: string }\n) {\n  \u002F\u002F 1. Ensure the wallet is on the correct chain\n  await switchChain(config, { chainId });\n\n  \u002F\u002F 2. Get wallet client with explicit chainId — avoids undefined and missing chain\n  const walletClient = await getWalletClient(config, { chainId });\n\n  \u002F\u002F 3. Execute the swap\n  const hash = await walletClient.sendTransaction({\n    to: swapTx.to as `0x${string}`,\n    data: swapTx.data as `0x${string}`,\n    value: BigInt(swapTx.value || '0'),\n  });\n\n  \u002F\u002F 4. Wait for confirmation\n  const publicClient = getPublicClient(config, { chainId });\n  if (!publicClient) throw new Error(`No public client configured for chainId ${chainId}`);\n  return publicClient.waitForTransactionReceipt({ hash });\n}\n```\n\n**Why this matters**:\n\n- `useWalletClient()` hook returns `{ data: undefined }` during async resolution, even after `useAccount()` shows connected\n- `getWalletClient(config, { chainId })` is a promise that resolves only when the client is ready, and includes the chain\n- `switchChain()` prevents \"chain mismatch\" errors when the wallet is on a different network than the swap\n\n### Backend Swap Script (Node.js)\n\n```typescript\nimport { createWalletClient, createPublicClient, http, isAddress, isHex, type Address } from 'viem';\nimport { privateKeyToAccount } from 'viem\u002Faccounts';\nimport { mainnet } from 'viem\u002Fchains';\n\nconst API_URL = 'https:\u002F\u002Ftrade-api.gateway.uniswap.org\u002Fv1';\nconst API_KEY = process.env.UNISWAP_API_KEY!;\n\nconst account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);\nconst publicClient = createPublicClient({ chain: mainnet, transport: http() });\nconst walletClient = createWalletClient({ account, chain: mainnet, transport: http() });\n\n\u002F\u002F Helper to prepare \u002Fswap request body — routing-aware permitData handling\nfunction prepareSwapRequest(quoteResponse: Record\u003Cstring, unknown>, signature?: string): object {\n  const { permitData, permitTransaction, ...cleanQuote } = quoteResponse;\n  const request: Record\u003Cstring, unknown> = { ...cleanQuote };\n\n  \u002F\u002F UniswapX (DUTCH_V2, DUTCH_V3, PRIORITY): permitData is for LOCAL signing only.\n  \u002F\u002F The \u002Fswap body must NOT include permitData — the order is already encoded\n  \u002F\u002F in quote.encodedOrder. Only the signature is needed.\n  const isUniswapX =\n    quoteResponse.routing === 'DUTCH_V2' ||\n    quoteResponse.routing === 'DUTCH_V3' ||\n    quoteResponse.routing === 'PRIORITY';\n\n  if (isUniswapX) {\n    if (signature) request.signature = signature;\n  } else {\n    \u002F\u002F CLASSIC: both signature and permitData required together, or both omitted\n    if (signature && permitData && typeof permitData === 'object') {\n      request.signature = signature;\n      request.permitData = permitData;\n    }\n  }\n\n  return request;\n}\n\n\u002F\u002F Validate swap response before broadcasting\nfunction validateSwap(swap: { data?: string; to?: string; from?: string }): void {\n  if (!swap?.data || swap.data === '' || swap.data === '0x') {\n    throw new Error('swap.data is empty - quote may have expired');\n  }\n  if (!isHex(swap.data)) {\n    throw new Error('swap.data is not valid hex');\n  }\n  if (!swap.to || !isAddress(swap.to) || !swap.from || !isAddress(swap.from)) {\n    throw new Error('Invalid address in swap response');\n  }\n}\n\nasync function executeSwap(tokenIn: Address, tokenOut: Address, amount: string, chainId: number) {\n  const ETH_ADDRESS = '0x0000000000000000000000000000000000000000';\n\n  \u002F\u002F 1. Check approval (for ERC20 tokens, not native ETH)\n  if (tokenIn !== ETH_ADDRESS) {\n    const approvalRes = await fetch(`${API_URL}\u002Fcheck_approval`, {\n      method: 'POST',\n      headers: {\n        'x-api-key': API_KEY,\n        'Content-Type': 'application\u002Fjson',\n        'x-universal-router-version': '2.0',\n      },\n      body: JSON.stringify({\n        walletAddress: account.address,\n        token: tokenIn,\n        amount,\n        chainId,\n      }),\n    });\n    const approvalData = await approvalRes.json();\n\n    if (approvalData.approval) {\n      const hash = await walletClient.sendTransaction({\n        to: approvalData.approval.to,\n        data: approvalData.approval.data,\n        value: BigInt(approvalData.approval.value || '0'),\n      });\n      await publicClient.waitForTransactionReceipt({ hash });\n    }\n  }\n\n  \u002F\u002F 2. Get quote\n  const quoteRes = await fetch(`${API_URL}\u002Fquote`, {\n    method: 'POST',\n    headers: {\n      'x-api-key': API_KEY,\n      'Content-Type': 'application\u002Fjson',\n      'x-universal-router-version': '2.0',\n    },\n    body: JSON.stringify({\n      swapper: account.address,\n      tokenIn,\n      tokenOut,\n      tokenInChainId: String(chainId),\n      tokenOutChainId: String(chainId),\n      amount,\n      type: 'EXACT_INPUT',\n      slippageTolerance: 0.5,\n    }),\n  });\n  const quoteResponse = await quoteRes.json(); \u002F\u002F Store FULL response\n\n  if (!quoteRes.ok) {\n    throw new Error(quoteResponse.detail || 'Quote failed');\n  }\n\n  \u002F\u002F 3. Execute swap - CRITICAL: spread quote response, strip null fields\n  const swapRequest = prepareSwapRequest(quoteResponse);\n\n  const swapRes = await fetch(`${API_URL}\u002Fswap`, {\n    method: 'POST',\n    headers: {\n      'x-api-key': API_KEY,\n      'Content-Type': 'application\u002Fjson',\n      'x-universal-router-version': '2.0',\n    },\n    body: JSON.stringify(swapRequest),\n  });\n  const swapData = await swapRes.json();\n\n  if (!swapRes.ok) {\n    throw new Error(swapData.detail || 'Swap request failed');\n  }\n\n  \u002F\u002F 4. Validate before broadcasting\n  validateSwap(swapData.swap);\n\n  const hash = await walletClient.sendTransaction({\n    to: swapData.swap.to,\n    data: swapData.swap.data,\n    value: BigInt(swapData.swap.value || '0'),\n  });\n  return publicClient.waitForTransactionReceipt({ hash });\n}\n```\n\n### Smart Contract Integration (Solidity)\n\n```solidity\n\u002F\u002F SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IUniversalRouter {\n    function execute(\n        bytes calldata commands,\n        bytes[] calldata inputs,\n        uint256 deadline\n    ) external payable;\n}\n\ninterface IERC20 {\n    function approve(address spender, uint256 amount) external returns (bool);\n}\n\ncontract SwapIntegration {\n    IUniversalRouter public immutable router;\n    address public constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;\n\n    constructor(address _router) {\n        router = IUniversalRouter(_router);\n    }\n\n    function swap(\n        bytes calldata commands,\n        bytes[] calldata inputs,\n        uint256 deadline\n    ) external payable {\n        router.execute{value: msg.value}(commands, inputs, deadline);\n    }\n\n    \u002F\u002F Approve token for Permit2 (one-time setup)\n    function approveToken(address token) external {\n        IERC20(token).approve(PERMIT2, type(uint256).max);\n    }\n}\n```\n\n---\n\n## Advanced Patterns\n\n### Smart Account Integration (ERC-4337)\n\nExecute Trading API swaps through ERC-4337 smart accounts with delegation. The pattern:\n\n1. Get swap calldata from Trading API (standard 3-step flow)\n2. Wrap the calldata in a delegation redemption execution\n3. Submit via bundler as a UserOperation\n\n```typescript\n\u002F\u002F After getting swap calldata from Trading API:\nconst { to, data, value } = swapResponse.swap;\n\n\u002F\u002F Wrap in delegation execution\nconst execution = {\n  target: to, \u002F\u002F Universal Router\n  callData: data,\n  value: BigInt(value),\n};\n\n\u002F\u002F Submit via bundler\nconst userOpHash = await bundlerClient.sendUserOperation({\n  account: delegateSmartAccount,\n  calls: [\n    {\n      to: delegationManagerAddress,\n      data: encodeFunctionData({\n        abi: delegationManagerAbi,\n        functionName: 'redeemDelegations',\n        args: [[[signedDelegation]], [0], [[execution]]],\n      }),\n      value: execution.value,\n    },\n  ],\n});\n```\n\n**Key considerations**:\n\n- Use legacy approvals (direct to Universal Router) instead of Permit2 for smart accounts — see [Approval Target](#approval-target-permit2-vs-legacy-direct-to-router)\n- Add 20-30% gas buffer for bundler gas estimation\n- Handle bundler-specific error codes separately from standard transaction errors\n\nSee [Advanced Patterns Reference](.\u002Freferences\u002Fadvanced-patterns.md#smart-account-integration-erc-4337) for the complete implementation with types and error handling.\n\n### WETH Handling on L2s\n\nOn L2 chains (Base, Optimism, Arbitrum), swaps outputting ETH may deliver WETH instead of native ETH. Always check and unwrap after swaps:\n\n```typescript\nimport { parseAbi, type Address } from 'viem';\n\nconst WETH_ABI = parseAbi([\n  'function balanceOf(address) view returns (uint256)',\n  'function withdraw(uint256)',\n]);\n\nconst WETH_ADDRESSES: Record\u003Cnumber, Address> = {\n  1: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',\n  10: '0x4200000000000000000000000000000000000006',\n  8453: '0x4200000000000000000000000000000000000006',\n  42161: '0x82aF49447D8a07e3bd95BD0d56f35241523fBab1',\n};\n\n\u002F\u002F After swap completes on an L2:\nconst wethAddress = WETH_ADDRESSES[chainId];\nif (wethAddress) {\n  const wethBalance = await publicClient.readContract({\n    address: wethAddress,\n    abi: WETH_ABI,\n    functionName: 'balanceOf',\n    args: [accountAddress],\n  });\n\n  if (wethBalance > 0n) {\n    const hash = await walletClient.writeContract({\n      address: wethAddress,\n      abi: WETH_ABI,\n      functionName: 'withdraw',\n      args: [wethBalance],\n    });\n    await publicClient.waitForTransactionReceipt({ hash });\n  }\n}\n```\n\nSee [Advanced Patterns Reference](.\u002Freferences\u002Fadvanced-patterns.md#weth-handling-on-l2s) for chain-specific WETH addresses and integration details.\n\n### Rate Limiting\n\nThe Trading API enforces rate limits (~10 requests\u002Fsecond per endpoint). For batch operations:\n\n- Add **100-200ms delays** between sequential API calls\n- Implement **exponential backoff with jitter** on 429 responses\n- **Cache approval results** — approvals rarely change between calls\n\n```typescript\n\u002F\u002F Exponential backoff for 429 responses\nasync function fetchWithRetry(url: string, init: RequestInit, maxRetries = 5): Promise\u003CResponse> {\n  for (let attempt = 0; attempt \u003C= maxRetries; attempt++) {\n    const response = await fetch(url, init);\n    if (response.status !== 429 && response.status \u003C 500) return response;\n    if (attempt === maxRetries) throw new Error(`Failed after ${maxRetries} retries`);\n\n    const delay = Math.min(200 * Math.pow(2, attempt) + Math.random() * 100, 10000);\n    await new Promise((resolve) => setTimeout(resolve, delay));\n  }\n  throw new Error('Unreachable');\n}\n```\n\nSee [Advanced Patterns Reference](.\u002Freferences\u002Fadvanced-patterns.md#rate-limiting-best-practices) for batch operation patterns and full retry implementation.\n\n---\n\n## Key Contract Addresses\n\n### Universal Router (v4)\n\nAddresses are per-chain. The legacy v1 address `0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD` is deprecated.\n\n| Chain       | ID      | Address                                      |\n| ----------- | ------- | -------------------------------------------- |\n| Ethereum    | 1       | `0x66a9893cc07d91d95644aedd05d03f95e1dba8af` |\n| Unichain    | 130     | `0xef740bf23acae26f6492b10de645d6b98dc8eaf3` |\n| Optimism    | 10      | `0x851116d9223fabed8e56c0e6b8ad0c31d98b3507` |\n| Base        | 8453    | `0x6ff5693b99212da76ad316178a184ab56d299b43` |\n| Arbitrum    | 42161   | `0xa51afafe0263b40edaef0df8781ea9aa03e381a3` |\n| Polygon     | 137     | `0x1095692a6237d83c6a72f3f5efedb9a670c49223` |\n| Blast       | 81457   | `0xeabbcb3e8e415306207ef514f660a3f820025be3` |\n| BNB         | 56      | `0x1906c1d672b88cd1b9ac7593301ca990f94eae07` |\n| Zora        | 7777777 | `0x3315ef7ca28db74abadc6c44570efdf06b04b020` |\n| World Chain | 480     | `0x8ac7bee993bb44dab564ea4bc9ea67bf9eb5e743` |\n| Avalanche   | 43114   | `0x94b75331ae8d42c1b61065089b7d48fe14aa73b7` |\n| Celo        | 42220   | `0xcb695bc5d3aa22cad1e6df07801b061a05a0233a` |\n| Soneium     | 1868    | `0x4cded7edf52c8aa5259a54ec6a3ce7c6d2a455df` |\n| Ink         | 57073   | `0x112908dac86e20e7241b0927479ea3bf935d1fa0` |\n| Monad       | 143     | `0x0d97dc33264bfc1c226207428a79b26757fb9dc3` |\n\nFor testnet addresses, see [Uniswap v4 Deployments](https:\u002F\u002Fdocs.uniswap.org\u002Fcontracts\u002Fv4\u002Fdeployments).\n\n### Permit2\n\n| Chain      | Address                                      |\n| ---------- | -------------------------------------------- |\n| All chains | `0x000000000022D473030F116dDEE9F6B43aC78BA3` |\n\n---\n\n## Troubleshooting\n\n### Common Issues\n\n| Issue                                                  | Solution                                                                                                                                                                                                     |\n| ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| \"Insufficient allowance\"                               | Call \u002Fcheck_approval first and submit approval tx                                                                                                                                                            |\n| \"Quote expired\"                                        | Increase deadline or re-fetch quote                                                                                                                                                                          |\n| \"Slippage exceeded\"                                    | Increase slippageTolerance or retry                                                                                                                                                                          |\n| \"Insufficient liquidity\"                               | Try smaller amount or different route                                                                                                                                                                        |\n| **\"Buffer is not defined\"**                            | Add Buffer polyfill (see Critical Implementation Notes)                                                                                                                                                      |\n| **On-chain revert with empty data**                    | Validate `swap.data` is non-empty hex before broadcasting                                                                                                                                                    |\n| **\"permitData must be of type object\"**                | Strip `permitData: null` from request - omit field entirely                                                                                                                                                  |\n| **\"quote does not match any of the allowed types\"**    | Don't wrap quote in `{quote: ...}` — spread into request body. Also check: for UniswapX routes, `permitData` must be omitted from the `\u002Fswap` body (see [API Validation Errors](#api-validation-errors-400)) |\n| **Received WETH instead of ETH on L2**                 | Check and unwrap WETH after swap (see [WETH Handling on L2s](#weth-handling-on-l2s))                                                                                                                         |\n| **429 Too Many Requests**                              | Implement exponential backoff and add delays between batch requests (see [Rate Limiting](#rate-limiting))                                                                                                    |\n| **415 on OPTIONS preflight \u002F CORS error**              | Set up a CORS proxy (see [CORS Proxy Configuration](#cors-proxy-configuration) in Browser Environment Setup)                                                                                                 |\n| **walletClient is undefined when wallet is connected** | Use `getWalletClient()` from `@wagmi\u002Fcore` instead of the `useWalletClient()` hook (see [wagmi v2 Integration Pitfalls](#wagmi-v2-integration-pitfalls))                                                     |\n| **\"Please provide a chain with the chain argument\"**   | Pass `chainId` to `getWalletClient(config, { chainId })`                                                                                                                                                     |\n| **Chain mismatch error on swap**                       | Call `switchChain()` before `getWalletClient()` (see [wagmi v2 Integration Pitfalls](#wagmi-v2-integration-pitfalls))                                                                                        |\n\n### API Validation Errors (400)\n\n| Error Message                                     | Cause                                                                    | Fix                                                                                                        |\n| ------------------------------------------------- | ------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------- |\n| `\"permitData\" must be of type object`             | Sending `permitData: null`                                               | Omit the field entirely when null                                                                          |\n| `\"quote\" does not match any of the allowed types` | Wrapping quote in `{quote: quoteResponse}`                               | Spread quote response: `{...quoteResponse}`                                                                |\n| `\"quote\" does not match any of the allowed types` | Including `permitData` in a UniswapX (DUTCH_V2\u002FV3\u002FPRIORITY) `\u002Fswap` body | Omit `permitData` for UniswapX routes — see [Signing vs. Submission](#uniswapx-signing-vs-submission-flow) |\n| `signature and permitData must both be present`   | Including only one Permit2 field (CLASSIC routes only)                   | Include both or neither for CLASSIC; omit `permitData` for UniswapX                                        |\n\n### API Error Codes\n\n| Code | Meaning                                                  |\n| ---- | -------------------------------------------------------- |\n| 400  | Invalid request parameters (see validation errors above) |\n| 401  | Invalid or missing API key                               |\n| 404  | No route found for pair                                  |\n| 429  | Rate limit exceeded                                      |\n| 500  | API error - implement exponential backoff retry          |\n\n### Pre-Broadcast Checklist\n\nBefore sending a swap transaction to the blockchain:\n\n1. **Verify `swap.data`** is non-empty hex (not `''`, not `'0x'`)\n2. **Verify addresses** - `swap.to` and `swap.from` are valid\n3. **Check quote freshness** - Re-fetch if older than 30 seconds\n4. **Validate gas** - Apply 10-20% buffer to estimates\n5. **Confirm balance** - User has sufficient token balance\n\n---\n\n## Additional Resources\n\n- [Universal Router GitHub](https:\u002F\u002Fgithub.com\u002FUniswap\u002Funiversal-router)\n- [Uniswap Docs](https:\u002F\u002Fdocs.uniswap.org)\n- [SDK Monorepo](https:\u002F\u002Fgithub.com\u002FUniswap\u002Fsdks)\n- [Permit2 Patterns](https:\u002F\u002Fgithub.com\u002Fdragonfly-xyz\u002Fuseful-solidity-patterns\u002Ftree\u002Fmain\u002Fpatterns\u002Fpermit2)\n",{"name":5,"model":33,"license":15,"metadata":54,"description":7,"allowed-tools":56},{"author":35,"version":55},"1.3.0","Read, Write, Edit, Glob, Grep, Bash(npm:*), Bash(npx:*), Bash(yarn:*), Bash(curl:*), WebFetch, Task(subagent_type:swap-integration-expert)","main","6c13f6f4ac5a3bc1e6b78cd2bb1704f122c4a73e","archive\u002Fupstream\u002Fchasebuild-agent-skills\u002Fweb3\u002Fskills\u002Fswap-integration",0,"https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit","https:\u002F\u002Fgithub.com\u002F0xharryriddle","https:\u002F\u002Fharryriddle.vercel.app","2026-04-11 11:49:51",{"source":8,"skillName":5,"commands":66,"prompt":76,"zipAvailable":77},[67,70,73],{"tool":68,"command":69},"npx","npx skills add 0xharryriddle\u002Fcodex-field-kit --skill swap-integration",{"tool":71,"command":72},"bunx","bunx skills add 0xharryriddle\u002Fcodex-field-kit --skill swap-integration",{"tool":74,"command":75},"pnpm","pnpm dlx skills add 0xharryriddle\u002Fcodex-field-kit --skill swap-integration","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Farchive\u002Fupstream\u002Fchasebuild-agent-skills\u002Fweb3\u002Fskills\u002Fswap-integration\u002FSKILL.md",true,[79],{"path":80,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":83,"sourceHtmlUrl":84},"references\u002Fadvanced-patterns.md","REFERENCE","参考文档",10077,"https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Farchive\u002Fupstream\u002Fchasebuild-agent-skills\u002Fweb3\u002Fskills\u002Fswap-integration\u002Freferences\u002Fadvanced-patterns.md",[86,114,133,143,168,194],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":93,"publishedAt":49},"01M6H7ZKE6MR33HC84QZ1TA6MV","vercel-react-best-practices","React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React\u002FNext.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.","https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Fskills\u002Fvercel-react-best-practices\u002FSKILL.md",[92],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},[94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113],"react best practices","react","vercel react best practices","best practices","vercel","tasks","data fetching","triggers","pages","next","performance optimization","refactoring","Next.js","Optimization","code","guidelines","react components","components","performance","writing",{"skillNo":115,"name":116,"nameZh":6,"description":117,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":118,"categories":119,"keywords":120,"publishedAt":49},"01M6H7ZGC2WK8SEKYHWDNTMDA9","swarm-planner","[EXPLICIT INVOCATION ONLY] Creates dependency-aware implementation plans optimized for parallel multi-agent execution.","https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Fskills\u002Fswarm-planner\u002FSKILL.md",[],[121,122,123,124,125,126,127,128,129,130,131,132],"swarm","swarm planner","planner","parallel","multi-agent","only","execution","plans","dependency","for","multi","implementation",{"skillNo":134,"name":135,"nameZh":6,"description":136,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":137,"categories":138,"keywords":139,"publishedAt":49},"01M6H7ZD93853RZCYQWH1D38TM","super-swarm-spark","Only to be triggered by explicit super-swarm-spark commands.","https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Fskills\u002Fsuper-swarm-spark\u002FSKILL.md",[],[140,121,141,126,142],"super swarm spark","spark","commands",{"skillNo":144,"name":145,"nameZh":6,"description":146,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":147,"categories":148,"keywords":149,"publishedAt":49},"01M6H7Z987QBY49JCCPT953EAZ","role-creator","Create and install Codex custom agent roles in ~\u002F.codex\u002Fconfig.toml, generate role config files, enforce supported keys, and guide users through required role inputs (model, reasoning effort, developer_instructions).","https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Fskills\u002Frole-creator\u002FSKILL.md",[],[150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,48,165,166,167],"role","creator","role creator","keys","users","roles","toml","enforce","install","guide","instructions","model","developer","reasoning","generate","config","codex","files",{"skillNo":169,"name":170,"nameZh":6,"description":171,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":172,"categories":173,"keywords":177,"publishedAt":49},"01M6H7Z5TRPMDQ7YSZQXPN1G60","read-github","Read and search GitHub repository documentation via gitmcp.io MCP service.\n\n**WHEN TO USE:**\n- User provides a GitHub URL\n- User mentions a specific repo in owner\u002Frepo format\n- User asks \"what does this repo do?\", \"read the docs for X repo\", or similar\n- User wants to search code or docs within a repo","https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Fskills\u002Fread-github\u002FSKILL.md",[174],{"categoryNo":175,"categoryName":176,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",[178,179,44,108,180,181,182,183,130,184,185,186,187,188,189,41,190,191,192,193],"github","read github","documentation","docs","MCP","search","when to use","URL","via","io","service","do","user","repo","format","repository",{"skillNo":195,"name":123,"nameZh":6,"description":196,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":197,"categories":198,"keywords":199,"publishedAt":49},"01M6H7Z215CTKYJ4Y1X6EQWN6M","Create comprehensive, phased implementation plans with sprints and atomic tasks. Use when user says: \"make a plan\", \"create a plan\", \"plan this out\", \"plan the implementation\", \"help me plan\", \"design a plan\", \"draft a plan\", \"write a plan\", \"outline the steps\", \"break this down into tasks\", \"what's the plan for\", or any similar planning request. Also triggers on explicit \"\u002Fplanner\" or \"\u002Fplan\" commands.","https:\u002F\u002Fgithub.com\u002F0xharryriddle\u002Fcodex-field-kit\u002Fblob\u002Fmain\u002Fskills\u002Fplanner\u002FSKILL.md",[],[123,200,130,201,202,203,101,128,142,204,205,41,43,206,207,208,209,48,99,210],"outline","atomic","with","sprints","draft","me","phased implementation","plan","help","planning","design"]