[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M78BE1QD2TFWZ8ZXBJWTCB3S":3,"skill-same:01M78BE1QD2TFWZ8ZXBJWTCB3S":66},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":29,"commitSha":30,"skillDirectory":31,"forksCount":14,"repositoryHtmlUrl":32,"repositoryHomepageUrl":33,"ownerHtmlUrl":34,"ownerBlogUrl":35,"ownerDescription":36,"updatedAt":37,"install":38,"resources":51},"01M78BE1QD2TFWZ8ZXBJWTCB3S","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.","Solizardking\u002Fskillhub-main","Solizardking","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F108096810?v=4","01M786KDB10AYV042N0F9BD5B5","Clawd","01M786NYYXSZK1D05WM8JQPC48",0,"MIT","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fpublic\u002Fapi\u002Fskills\u002Fswap-integration\u002FSKILL.md",[],[],"2026-11-15 14:19:17",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 **`bundlerClient.sendUserOperation()`** — always use the viem bundler client's\n   `sendUserOperation` method (not a custom wrapper function)\n\n> **REQUIRED:** The final submission step MUST use `bundlerClient.sendUserOperation()` from the\n> viem permissionless\u002Fbundler client. Do NOT write a custom `submitUserOperation` wrapper that\n> bypasses this — the bundler client handles UserOperation construction, gas estimation, and\n> submission automatically.\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 — use sendUserOperation directly\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 **`bundlerClient.sendUserOperation()`** — always use the viem bundler client's\n   `sendUserOperation` method (not a custom wrapper function)\n\n> **REQUIRED:** The final submission step MUST use `bundlerClient.sendUserOperation()` from the\n> viem permissionless\u002Fbundler client. Do NOT write a custom `submitUserOperation` wrapper that\n> bypasses this — the bundler client handles UserOperation construction, gas estimation, and\n> submission automatically.\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 — use sendUserOperation directly\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":24,"license":15,"metadata":25,"description":7,"allowed-tools":28},"opus",{"author":26,"version":27},"uniswap","1.3.0","Read, Write, Edit, Glob, Grep, Bash(npm:*), Bash(npx:*), Bash(yarn:*), Bash(curl:*), WebFetch, Task(subagent_type:swap-integration-expert)","main","be3de0244dc1a57e323d8160787ebb40fb64930e","public\u002Fapi\u002Fskills\u002Fswap-integration","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main","https:\u002F\u002Fskills.x402.wtf","https:\u002F\u002Fgithub.com\u002FSolizardking","https:\u002F\u002Fmusebook.trade","Got a mile high and never came down","2026-10-08 23:20:13",{"source":8,"skillName":5,"commands":39,"prompt":49,"zipAvailable":50},[40,43,46],{"tool":41,"command":42},"npx","npx skills add Solizardking\u002Fskillhub-main --skill swap-integration",{"tool":44,"command":45},"bunx","bunx skills add Solizardking\u002Fskillhub-main --skill swap-integration",{"tool":47,"command":48},"pnpm","pnpm dlx skills add Solizardking\u002Fskillhub-main --skill swap-integration","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fpublic\u002Fapi\u002Fskills\u002Fswap-integration\u002FSKILL.md",true,[52,58,62],{"path":53,"resourceType":54,"resourceTypeDesc":55,"sizeBytes":56,"sourceHtmlUrl":57},"metadata.json","REFERENCE","参考文档",477,"https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fpublic\u002Fapi\u002Fskills\u002Fswap-integration\u002Fmetadata.json",{"path":59,"resourceType":54,"resourceTypeDesc":55,"sizeBytes":60,"sourceHtmlUrl":61},"references\u002Fadvanced-patterns.md",10077,"https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fpublic\u002Fapi\u002Fskills\u002Fswap-integration\u002Freferences\u002Fadvanced-patterns.md",{"path":63,"resourceType":54,"resourceTypeDesc":55,"sizeBytes":64,"sourceHtmlUrl":65},"verification.json",1341,"https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fpublic\u002Fapi\u002Fskills\u002Fswap-integration\u002Fverification.json",[67,74,81,88,95,103],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M78E0TGCAMNPS207BA3G07S7","zkrouter","Self-hosted OpenAI-compatible LLM router — smart tier-based routing, ZK-stamped routing decisions, mode overrides, free OpenRouter at install via the Birth bot. Save 60-80% on inference costs by routing to the cheapest capable model across 12+ OpenRouter models.","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fzkrouter\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M78E0R1Z8BDT6EDTHY17MTNB","zk","For custom ZK Solana programs and privacy-preserving applications to prevent double spending. Guide to integrate rent-free nullifier PDAs for double-spend prevention.","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fzk\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M78E0P3ZTZ1YWF8MD5MM23QE","zk-omni-messaging","Zero-knowledge omnichain messaging between Robinhood Chain and Solana using CheshireZkOmniMessenger (msgType 4) with nullifier anti-replay and the zk-omni-relayer service.","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fzk-omni-messaging\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M78E0JXZ2PNB1896VXAGDBWD","zerion-wallet-data","Use when the user asks to check a wallet's portfolio, token balances, DeFi positions, PnL, transaction history, or NFTs. Provides interpreted on-chain data across 40+ EVM chains and Solana via x402 pay-per-request or API key — no raw RPC decoding needed.","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fzerion-wallet-data\u002FSKILL.md",[],[],{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":99,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":19},"01M78E0G14FH9GRRTQYMKD5E59","youtube-clipper","YouTube 视频智能剪辑工具。下载视频和字幕，AI 分析生成精细章节（几分钟级别）， 用户选择片段后自动剪辑、翻译字幕为中英双语、烧录字幕到视频，并生成总结文案。 使用场景：当用户需要剪辑 YouTube 视频、生成短视频片段、制作双语字幕版本时。 关键词：视频剪辑、YouTube、字幕翻译、双语字幕、视频下载、clip video","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fyoutube-clipper\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fyoutube-clipper\u002FSKILL.md",[],[],{"skillNo":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":19},"01M78E0C2ZYA99CFFDNB7ZMK5S","yield-optimization","Multi-chain yield optimization via yield.xyz (StakeKit). Discover 2,988+ yield opportunities across 75+ blockchains, build deposit\u002Fwithdrawal transactions with shell scripts, and sign them with a MoonPay wallet. Use when the user wants to earn yield, find the best lending or staking rate, enter\u002Fexit a position, or check portfolio balances.","https:\u002F\u002Fgithub.com\u002FSolizardking\u002Fskillhub-main\u002Fblob\u002Fmain\u002Fskills\u002Fyield-optimization\u002FSKILL.md",[],[]]