Squid 백서

Squid

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 27쪽 중 15쪽

tatus = async (params: any) => { const result = await axios.get("https://v2.api.squidrouter.com/v2/status", { params, headers: { "x-integrator-id": integratorId, }, }); return result.data; }; (async () => { const params = { fromAddress: signer.address, fromChain: fromChainId, fromToken: fromToken, fromAmount: fromAmount, toChain: toChainId, toToken: toToken, toAddress: signer.address, quoteOnly: false, }; console.log("Parameters:", params); // 1. Get the route const routeResult = await getRoute(params); const route = routeResult.data.route; const requestId = routeResult.requestId; // Extract quoteId (required for Squid Intents status tracking) const quoteId = route?.estimate?.actions?.[0]?.coralV2Order?.quoteId || route?.estimate?.quoteId || route?.quoteId || routeResult.data?.quoteId; console.log("Route received. Expected output:", route.estimate.toAmount); console.log("quoteId:", quoteId); const transactionRequest = route.transactionRequest; let depositTxVerificationSignature: string | undefined; // 2. Handle DEPOSIT_ADDRESS_WITH_SIGNATURE route type if ( transactionRequest.type === "DEPOSIT_ADDRESS_WITH_SIGNATURE" || transactionRequest.routeType === "DEPOSIT_ADDRESS_WITH_SIGNATURE" ) { console.log("Route type is DEPOSIT_ADDRESS_WITH_SIGNATURE, skipping ERC-20 approval..."); // Sign the order hash const orderHash = transactionRequest.signatureRequired; if (orderHash) { depositTxVerificationSignature = await signer.signMessage(orderHash); console.log("Generated deposit verification signature"); } } // 3. Poll estimateGas to confirm token association console.log("Verifying Hedera token association on deposit address..."); for (let i = 0; i < 15; i++) { try { await provider.estimateGas({ from: signer.address, to: transactionRequest.target, data: transactionRequest.data, value: transactionRequest.value, }); console.log("Token association confirmed. Proceeding with swap..."); break; } catch (e) { if (i === 14) { console.warn("Token association polling timed out. Attempting execution anyway..."); } else { await new Promise((resolve) => setTimeout(resolve, 1000)); } } } // 4. Execute the transaction const tx = await signer.sendTransaction({ to: transactionRequest.target, data: transactionRequest.data, value: transactionRequest.value, gasPrice: transactionRequest.gasPrice, gasLimit: transactionRequest.gasLimit, }); console.log("Transaction broadcasted:", tx.hash); const txReceipt = await tx.wait(); console.log("Transaction confirmed!"); // 5. Poll status until complete const statusParams: any = { transactionId: txReceipt!.hash, requestId: requestId, fromChainId: fromChainId, toChainId: toChainId, bridgeType: "rfq", quoteId: quoteId, }; // Attach the deposit verification signature for status tracking if (depositTxVerificationSignature) { statusParams.depositTxVerificationSignature = depositTxVerificationSignature; } const completedStatuses = ["success", "partial_success", "needs_gas", "not_found"]; const maxRetries = 100; let retryCount = 0; let status; do { try { status = await getStatus(statusParams); console.log(`Status: ${status.squidTransactionStatus}`); } catch (error: any) { if (error.response && error.response.status === 404) { retryCount++; if (retryCount >= maxRetries) { console.error("Max retries reached."); break; } console.log("Transaction not found. Retrying in 5s..."); await new Promise((resolve) => setTimeout(resolve, 5000)); continue; } throw error; } if (status && !completedStatuses.includes(status.squidTransactionStatus)) { await new Promise((resolve) => setTimeout(resolve, 5000)); } } while (!status || !completedStatuses.includes(status.squidTransactionStatus)); console.log("Swap complete!"); console.log(`Track on Squid Scanner: https://scan.squidrouter.com/tx/${txReceipt!.hash}`); })(); ``` *** ## SDK Integration The Squid SDK handles much of the Hedera-specific logic automatically. For `DEPOSIT_ADDRESS_WITH_SIGNATURE` routes, `executeRoute()` will: * Automatically sign the order hash (`signatureRequired`) * Execute the deposit transaction * Return the `depositTxVerificationSignature` in the response You are still responsible for: * Polling `estimateGas` to wait for token association before calling `executeRoute()` * Passing the `depositTxVerificationSignature` and `quoteId` to the status endpoint ### Full Working Example ```typescript import { Squid } from "@0xsquid/sdk"; import { ethers } from "ethers"; import * as dotenv from "dotenv"; dotenv.config(); const privateKey: string = process.env.PRIVATE_KEY!; const integratorId: string = process.env.INTEGRATOR_ID!; const FROM_CHAIN_RPC: string = process.env.FROM_CHAIN_RPC_ENDPOINT!; // Define chain and token parameters const fromChainId = "295"; // Hedera const fromToken = "0x000000000000000000000000000000000006f89a"; // USDC on Hedera const fromAmount = "2000"; const toChainId = "42161"; // Arbitrum const toToken = "0xaf88d065e77c8cc2239327c5edb3a432268e5831"; // USDC on Arbitrum // Set up provider and signer const provider = new ethers.JsonRpcProvider(FROM_CHAIN_RPC); const signer = new ethers.Wallet(privateKey, provider); // Initialize Squid SDK const getSDK = (): Squid => { const squid = new Squid({ baseUrl: "https://v2.api.squidrouter.com", integratorId: integratorId, }); return squid; }; (async () => { const squid = getSDK(); await squid.init(); console.log("Squid SDK initialized"); // 1. Get the route const params = { fromAddress: signer.address, fromChain: fromChainId, fromToken: fromToken, fromAmount: fromAmount, toChain: toChainId, toToken: toToken, toAddress: signer.address, }; const { route, requestId } = await squid.getRoute(params); // Extract quoteId (required for Squid Intents status tracking) const quoteId = (route as any).estimate?.actions?.[0]?.coralV2Order?.quoteId || (route as any).estimate?.quoteId || (route as any).quoteId; console.log("Route received. Expected output:", route.estimate.toAmount); // 2. Poll estimateGas to confirm token association if (route.transactionRequest) { const txReq = route.transactionRequest as any; console.log("Verifying Hedera token association on deposit address..."); for (let i = 0; i < 15; i++) { try { await provider.estimateGas({ from: signer.address, to: txReq.target, data: txReq.data, value: txReq.value, }); console.log("Token association confirmed. Proceeding..."); break; } catch (e) { if (i === 14) { console.warn("Polling timed out. Executing anyway..."); } else { await new Promise((resolve) => setTimeout(resolve, 1000)); } } } } // 3. Execute the route (SDK handles orderHash signing automatically) const response = await squid.executeRoute({ signer: signer as any, route, }); // 4. Extract transaction hash and deposit verification signature let txHash = "unknown"; let depositTxVerificationSignature: string | undefined; if (response && typeof response === "object") { if ("hash" in response) { txHash = response.hash as string; await (response as any).wait?.(); } else if ("transactionHash" in response) { txHash = (response as any).transactionHash; } if ("depositTxVerificationSignature" in response) { depositTxVerificationSignature = (response as any).depositTxVerificationSignature; } } console.log(`Transaction confirmed: ${txHash}`); console.log(`Track on Squid Scanner: https://scan.squidrouter.com/tx/${txHash}`); // 5. Poll status until complete const statusParams: any = { transactionId: txHash, requestId: requestId, integratorId: integratorId, fromChainId: fromChainId, toChainId: toChainId, bridgeType: "rfq", quoteId: quoteId, }; if (depositTxVerificationSignature) { statusParams.depositTxVerificationSignature = depositTxVerificationSignature; } const completedStatuses = ["success", "partial_success", "needs_gas", "not_found"]; const maxRetries = 100; let retryCount = 0; let status; do { try { await new Promise((resolve) => setTimeout(resolve, 5000)); status = await squid.getStatus(statusParams); console.log(`Status: ${status.squidTransactionStatus}`); } catch (error: unknown) { if ( error instanceof Error && (error as any).response?.status === 404 ) { retryCount++; if (retryCount >= maxRetries) { console.error("Max retries reached."); break; } console.log("Transaction not found. Retrying..."); continue; } throw error; } } while ( !status || !completedStatuses.includes(status.squidTransactionStatus as string) ); console.log("Swap complete!"); })(); ``` *** ## Status Tracking Hedera routes are powered by Squid Intents, which **requires** both `quoteId` and `depositTxVerificationSignature` for status polling. | Parameter | Description | | -------------------------------- | ----------------------------------------------------------- | | `transactionId` | The deposit transaction hash | | `fromChainId` | `295` (Hedera) | | `toChainId` | The destination chain ID | | `quoteId` | Returned in the route response — required for Squid Intents | | `depositTxVerificationSignature` | The signed order hash — required for Hedera routes | | `bridgeType` | `rfq` | ```typescript const statusParams = { transactionId: txHash, fromChainId: "295", toChainId: toChainId, quoteId: quoteId, depositTxVerificationSignature: depositTxVerificationSignature, bridgeType: "rfq", }; const status = await axios.get("https://v2.api.squidrouter.com/v2/status", { params: statusParams, headers: { "x-integrator-id": "<your-integrator-id>" }, }); ``` > **Important:** A Squid Intents transaction will not be trackable unless status is polled with the `quoteId`. See the [Integrating Squid Intents](/api-and-sdk-integration/coral-intent-swaps/integrating-squid-intents) guide for full status polling details. *** ## Code Examples ### API Examples | Route | Example | | ------------ | ------------------------------------------------------------------------------------------------- | | Hedera → EVM | [hederaToArbitrumSwap](https://github.com/0xsquid/examples/tree/main/V2/api/hederaToArbitrumSwap) | ### SDK Examples | Route | Example | | ------------ | ------------------------------------------------------------------------------------------------- | | Hedera → EVM | [hederaToArbitrumSwap](https://github.com/0xsquid/examples/tree/main/V2/sdk/hederaToArbitrumSwap) | *** ## Important Notes * **EVM-compatible wallets only** — Hedera integration uses Hedera's EVM-compatible layer. You need an Ethereum-style private key and can interact with Hedera using standard `ethers.js` tooling and a Hedera JSON-RPC endpoint. * **No ERC-20 approval needed** — `DEPOSIT_ADDRESS_WITH_SIGNATURE` routes bypass the standard approval flow. Do not call `approve()` for these routes. * **Token association is asynchronous** — Always poll `estimateGas` before sending the deposit transaction to ensure the deposit address has completed HTS token association. Skipping this step may result in a failed transaction. * **Order hash signing is mandatory** — The `signatureRequired` field must be signed and the resulting `depositTxVerificationSignature` must be passed to the `/v2/status` endpoint for transaction tracking. * **`quoteId` is required for status calls** — All Squid Intents transactions (including Hedera routes) require the `quoteId` parameter when polling the status endpoint. For a full reference of all transaction types across all chains, see the [Transaction Types](/api-and-sdk-integration/key-concepts/transaction-types) page. # Canton Integration Integrate cross-chain swaps from Canton to EVM chains using Squid. Canton support is powered by [**Squid Intents**](/api-and-sdk-integration/coral-intent-swaps) — Squid's intent-based execution protocol for fast, solver-driven cross-chain settlement. > **Squid Intents must be enabled on your integrator ID.** Reach out to the Squid team to request Squid Intents access before integrating with Canton. *** ## Canton Parameters | Parameter | Value | | ------------ | -------- | | **Chain ID** | `canton` | ### Supported Tokens | Token | Address | | ----------------------------------- | --------------------------------------------------------------------------- | | **Canton Coin (CC)** — native asset | `DSO::1220b1431ef217342db44d516bb9befde802be7d8899637d290895fa58880f19accc` | Canon Coin (CC) is the native asset on Canton. Additional tokens are supported — query the [Supported Tokens endpoint](/chains-and-tokens/get-supported-tokens-and-chains) with `chainId=canton` to get the full list of available tokens. > Token addresses on Canton follow the format `admin::fingerprint` for the native Canton Coin, or `instrumentId::admin::fingerprint` for CIP-056 tokens (e.g., `USDCx::decentralized-usdc-admin::12208...`). *** ## Key Concepts ### Transaction Type: `DEPOSIT_ADDRESS_DIRECT_TRANSFER` Canton routes use the `DEPOSIT_ADDRESS_DIRECT_TRANSFER` transaction type. Unlike standard EVM routes, this type: * **Does not require ERC-20 approval** — Canton is not EVM-compatible * **Returns a deposit address** — the route response includes a `target` field containing the deposit address for funds * **Uses the order hash as a memo** — the `data` field in the transaction request contains the order hash, which must be included as a transfer memo when sending funds Canton transactions can be executed in two ways: 1. **Connected wallet (browser)**: Using a CIP-103-compatible Canton wallet, the transfer is built using the Splice token-standard `TransferFactory` and submitted via `prepareExecuteAndWait` 2. **Deposit address**: Send funds directly to the deposit address with the order hash as a memo from any Canton wallet > **Why can't Canton swaps be fully automated from a script?** > > Unlike EVM chains where a private key can be imported to sign transactions programmatically, Canton wallets use the **CIP-103 protocol** — a browser-based wallet discovery and signing standard. Wallet keys are managed entirely within browser extensions (Send, C8, Nightly) and communicate via `window.postMessage`. There is no exportable private key or Node.js-compatible signing SDK for Canton. > > The API and SDK examples handle everything that can be done programmatically: requesting a route, displaying deposit details, and polling transaction status. The only manual step is sending funds to the deposit address from your Canton wallet with the order hash as the memo. > > For fully automated execution in a browser environment, use the [Squid Widget](/widget-integration/add-a-widget/widget), which connects to Canton wallets via CIP-103. ### Canton Address Format Canton addresses use the format `name::fingerprint`, where `name` is an identifier and `fingerprint` is a `1220`-prefixed SHA-256 hash (68 hex characters total). Example: `DSO::1220b1431ef217342db44d516bb9befde802be7d8899637d290895fa58880f19accc` ### Token Pre-Approval (EVM → Canton) Canton uses the **CIP-56 token standard**, which follows an **offer-and-acceptance model** for token transfers. Unlike EVM's push-only model (where tokens are sent directly to a recipient), Canton requires recipients to explicitly agree to receive a token before it can be credited to their wallet. To streamline this, Canton supports **`TransferPreapproval`** — a smart contract that pre-authorizes incoming transfers for a specific token. Without a preapproval in place, incoming tokens arrive as a pending "transfer offer" that the recipient must manually accept in their wallet. **How this affects integrations:** * **Squid Widget**: The widget handles `TransferPreapproval` checks automatically. If a user's Canton wallet does not have a preapproval for the receiving token, the widget will prompt them to set one up before executing the swap. * **API / SDK**: The `TransferPreapproval` is not exposed as an API endpoint. When building EVM → Canton swaps via the API or SDK, the route is a standard EVM transaction (`DEPOSIT_ADDRESS_CALLDATA`). The Canton-side token delivery is handled by Squid's backend. However, the user's Canton wallet must have a `TransferPreapproval` for the destination token, or they will need to manually accept the transfer offer in their wallet. *** ## API Integration ### Canton → EVM Swap The following example demonstrates a full Canton-to-EVM swap using the Squid API directly. It sends Canton Coin (CC) to USDC on Base using the deposit-address pattern. ```typescript // Canton to EVM Swap Using Squid API (Squid Intents) import axios from "axios"; import * as dotenv from "dotenv"; dotenv.config(); // Load environment variables const cantonAddress: string = process.env.CANTON_ADDRESS!; const integratorId: string = process.env.INTEGRATOR_ID!; // Define swap parameters const fromChainId = "canton"; const fromToken = "DSO::1220b1431ef217342db44d516bb9befde802be7d8899637d290895fa58880f19accc"; // Canton Coin (CC) const fromAmount = "10000000000"; // 1 CC (Canton Coin uses 10 decimals) const toChainId = "8453"; // Base const toToken = "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913"; // USDC on Base // Get the optimal route for the swap const getRoute = async (params: any) => { try { const result = await axios.post( "https://v2.api.squidrouter.com/v2/route", params, { headers: { "x-integrator-id": integratorId, "Content-Type": "application/json", }, } ); const requestId = result.headers["x-request-id"]; return { data: result.data, requestId: requestId }; } catch (error: any) { if (error.response) { console.error("API error:", error.response.data); } throw error; } }; // Get the status of the transaction const getStatus = async (params: any) => { try { const result = await axios.get("https://v2.api.squidrouter.com/v2/status", { params, headers: { "x-integrator-id": integratorId, }, }); return result.data; } catch (error: any) { if (error.response) { console.error("API error:", error.response.data); } throw error; } }; // Poll transaction status until completion const updateTransactionStatus = async ( requestId: string, quoteId: string ) => { const getStatusParams: any = { requestId: requestId, fromChainId: fromChainId, toChainId: toChainId, quoteId: quoteId, }; let status; const completedStatuses = ["success", "partial_success", "needs_gas", "not_found"]; const maxRetries = 30; let retryCount = 0; do { try { status = await getStatus(getStatusParams); console.log(`Route status: ${status.squidTransactionStatus}`); } catch (error: any) { if (error.response && error.response.status === 404) { retryCount++; if (retryCount >= maxRetries) { console.error("Max retries reached. Transaction not found."); break; } await new Promise((resolve) => setTimeout(resolve, 5000)); continue; } else { throw error; } } if (status && !completedStatuses.includes(status.squidTransactionStatus)) { await new Promise((resolve) => setTimeout(resolve, 5000)); } } while (!(status && completedStatuses.includes(status.squidTransactionStatus))); console.log("Swap fully confirmed!"); }; // Main function (async () => { console.log(`Canton address: ${cantonAddress}`); const params = { fromAddress: cantonAddress, fromChain: fromChainId, fromToken: fromToken, fromAmount: fromAmount, toChain: toChainId, toToken: toToken, toAddress: "0xYourEVMAddress", // Replace with your destination EVM wallet quoteOnly: false, }; console.log("Parameters:", params); // Get the swap route const routeResult = await getRoute(params); const route = routeResult.data.route; const requestId = routeResult.requestId; // Extract quoteId for Squid Intents transactions const quoteId = route?.estimate?.actions?.[0]?.coralV2Order?.quoteId || route?.estimate?.quoteId || route?.quoteId || routeResult.data?.quoteId; console.log("Calculated route. Target output:", route.estimate.toAmount); console.log("requestId:", requestId); console.log("quoteId:", quoteId); const transactionReque
프로젝트로 돌아가기