Squid 백서

Squid

원문

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

tTarget}`); } catch (error) { console.error('Approval failed:', error); throw error; } }; // Main function (async () => { // Initialize Squid SDK const squid = getSDK(); await squid.init(); console.log("Initialized Squid SDK"); // Set up parameters for swapping tokens const params = { fromAddress: await signer.getAddress(), fromChain: fromChainId, fromToken: fromToken, fromAmount: amount, toChain: toChainId, toToken: toToken, toAddress: await signer.getAddress() }; console.log("Parameters:", params); // Printing the parameters for QA // Get the swap route using Squid SDK const { route, requestId } = await squid.getRoute(params); const quoteId = route.quoteId; // Save quoteId — required for Squid Intents status tracking console.log("Calculated route:", route.estimate.toAmount); console.log("quoteId:", quoteId); // Get the transaction request from route if (!route.transactionRequest) { console.error("No transaction request in route"); process.exit(1); } // For SquidData objects, we need to check what type it is and extract the target let target: string; if ('target' in route.transactionRequest) { target = route.transactionRequest.target; } else { console.error("Cannot determine target address from transaction request"); console.log("Transaction request:", route.transactionRequest); process.exit(1); } // Approve the target to spend fromAmount of fromToken await approveSpending(target, fromToken, amount); // Execute the swap transaction const txResponse = await squid.executeRoute({ signer: signer as any, // Cast to any to bypass type checking issues route, }); // Handle the transaction response - could be an ethers v6 TransactionResponse or something else let txHash: string = 'unknown'; if (txResponse && typeof txResponse === 'object') { if ('hash' in txResponse) { // This is an ethers TransactionResponse txHash = txResponse.hash as string; await (txResponse as any).wait?.(); // Wait for the transaction to be mined if possible } else if ('transactionHash' in txResponse) { // This might be a v5 style response or custom Squid format txHash = (txResponse as any).transactionHash as string; } else { // Fallback - try to find a hash property txHash = (txResponse as any).hash as string || 'unknown'; } } // Show the transaction receipt with Axelarscan link const axelarScanLink = "https://axelarscan.io/gmp/" + txHash; console.log(`Finished! Check Axelarscan for details: ${axelarScanLink}`); // Wait a few seconds before checking the status await new Promise((resolve) => setTimeout(resolve, 5000)); // Parameters for checking the status of the transaction const getStatusParams = { transactionId: txHash, requestId: requestId, integratorId: integratorId, quoteId: quoteId, // Required for Squid Intents transactions }; const completedStatuses = ["success", "partial_success", "needs_gas", "not_found"]; const maxRetries = 10; // Maximum number of retries for status check let retryCount = 0; // Get the initial status let status = await squid.getStatus(getStatusParams); console.log(`Initial route status: ${status.squidTransactionStatus}`); // Loop to check the transaction status until it is completed or max retries are reached do { try { // Wait a few seconds before checking the status await new Promise((resolve) => setTimeout(resolve, 5000)); // Retrieve the transaction's route status status = await squid.getStatus(getStatusParams); // Display the route status console.log(`Route status: ${status.squidTransactionStatus}`); } catch (error: unknown) { // Handle error if the transaction status is not found if (error instanceof Error && (error as any).response && (error as any).response.status === 404) { retryCount++; if (retryCount >= maxRetries) { console.error("Max retries reached. Transaction not found."); break; } console.log("Transaction not found. Retrying..."); continue; } else { throw error; } } } while (status && !completedStatuses.includes(status.squidTransactionStatus)); // Wait for the transaction to be executed console.log("Swap transaction executed:", txHash); })(); ``` # Staking Example This example walks you through how to implement the SDK to allow a wallet to swap from Binance to Arbitrum and lend on Radiant. Download the full example [**here**](https://github.com/0xsquid/examples/tree/main/V2/sdk/swapEVMtoEVMAndLendPosthook)**.** ```typescript // Import necessary libraries import { ethers } from "ethers"; import { Squid } from "@0xsquid/sdk"; import { ChainType, EvmContractCall } from "@0xsquid/squid-types"; // Load environment variables from the .env file import * as dotenv from "dotenv"; dotenv.config(); // Load environment variables from .env file const privateKey: string = process.env.PRIVATE_KEY!; const integratorId: string = process.env.INTEGRATOR_ID!; const FROM_CHAIN_RPC: string = process.env.RPC_ENDPOINT!; const aaveArbitrumPoolAddress: string = "0x794a61358D6845594F94dc1DB02A252b5b4814aD"; // Aave v3 pool on Arbitrum const usdcArbitrumAddress: string = "0xaf88d065e77c8cC2239327C5EDb3A432268e5831"; // Define chain and token addresses const fromChainId = "56"; // Binance const toChainId = "42161"; // Arbitrum const fromToken = "0x55d398326f99059fF775485246999027B3197955"; // Define departing token // Define amount to be sent const amount = "100000000000000000"; // Set up JSON RPC provider and signer using the private key and RPC URL const provider = new ethers.JsonRpcProvider(FROM_CHAIN_RPC); const signer = new ethers.Wallet(privateKey, provider); // Import erc20 contract ABI import erc20Abi from "../abi/erc20Abi"; // Define Aave pool ABI (simplified for this example) const aavePoolAbi = [ "function supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external" ]; // Function to get Squid SDK instance const getSDK = (): Squid => { const squid = new Squid({ baseUrl: "https://v2.api.squidrouter.com", integratorId: integratorId, }); return squid; }; // Function to approve the transactionRequest.target to spend fromAmount of fromToken const approveSpending = async (transactionRequestTarget: string, fromToken: string, fromAmount: string) => { const erc20Abi = [ "function approve(address spender, uint256 amount) public returns (bool)" ]; const tokenContract = new ethers.Contract(fromToken, erc20Abi, signer); try { const tx = await tokenContract.approve(transactionRequestTarget, fromAmount); await tx.wait(); console.log(`Approved ${fromAmount} tokens for ${transactionRequestTarget}`); } catch (error) { console.error('Approval failed:', error); throw error; } }; // Main function (async () => { // Initialize Squid SDK const squid = getSDK(); await squid.init(); console.log("Initialized Squid SDK"); // Creating Contract interfaces // Approve the Aave pool contract to spend the USDC const erc20Interface = new ethers.Interface(erc20Abi); const approvalData = erc20Interface.encodeFunctionData("approve", [ aaveArbitrumPoolAddress, ethers.MaxUint256, // ethers v6 uses MaxUint256 directly on ethers ]); // Create contract interface and encode supply function for Aave lending pool const aavePoolInterface = new ethers.Interface(aavePoolAbi); const userAddress = await signer.getAddress(); const supplyData = aavePoolInterface.encodeFunctionData( "supply", [ usdcArbitrumAddress, "0", // Amount will be replaced with the full token balance userAddress, 0, // referralCode ] ); // Set up parameters for swapping tokens and depositing into Aave lending pool const params = { fromAddress: userAddress, fromChain: fromChainId, fromToken: fromToken, fromAmount: amount, toChain: toChainId, toToken: usdcArbitrumAddress, toAddress: userAddress, quoteOnly: false, postHook: { chainType: ChainType.EVM, calls: [ { chainType: ChainType.EVM, callType: 1, // SquidCallType.FULL_TOKEN_BALANCE target: usdcArbitrumAddress, value: "0", // this will be replaced by the full native balance of the multicall after the swap callData: approvalData, payload: { tokenAddress: usdcArbitrumAddress, inputPos: 1, }, estimatedGas: "50000", } as EvmContractCall, { chainType: ChainType.EVM, callType: 1, // SquidCallType.FULL_TOKEN_BALANCE target: aaveArbitrumPoolAddress, value: "0", callData: supplyData, payload: { tokenAddress: usdcArbitrumAddress, inputPos: 1, }, estimatedGas: "200000", } as EvmContractCall, ], provider: "Aave", description: "Deposit to Aave on Arbitrum", logoURI: "https://app.aave.com/favicon.ico", }, }; console.log("Parameters:", params); // Printing the parameters for QA // Get the swap route using Squid SDK const { route, requestId } = await squid.getRoute(params); const quoteId = route.quoteId; // Save quoteId — required for Squid Intents status tracking console.log("Calculated route:", route.estimate.toAmount); console.log("quoteId:", quoteId); // Get the transaction request from route if (!route.transactionRequest) { console.error("No transaction request in route"); process.exit(1); } // For SquidData objects, we need to check what type it is and extract the target let target: string; if ('target' in route.transactionRequest) { target = route.transactionRequest.target; } else { console.error("Cannot determine target address from transaction request"); console.log("Transaction request:", route.transactionRequest); process.exit(1); } // Approve the target to spend fromAmount of fromToken await approveSpending(target, fromToken, amount); // Execute the swap transaction const txResponse = await squid.executeRoute({ signer: signer as any, // Cast to any to bypass type checking issues route, }); // Handle the transaction response - could be an ethers v6 TransactionResponse or something else let txHash: string = 'unknown'; if (txResponse && typeof txResponse === 'object') { if ('hash' in txResponse) { // This is an ethers TransactionResponse txHash = txResponse.hash as string; await (txResponse as any).wait?.(); // Wait for the transaction to be mined if possible } else if ('transactionHash' in txResponse) { // This might be a v5 style response or custom Squid format txHash = (txResponse as any).transactionHash as string; } else { // Fallback - try to find a hash property txHash = (txResponse as any).hash as string || 'unknown'; } } // Show the transaction receipt with Axelarscan link const axelarScanLink = "https://axelarscan.io/gmp/" + txHash; console.log(`Finished! Check Axelarscan for details: ${axelarScanLink}`); // Wait a few seconds before checking the status await new Promise((resolve) => setTimeout(resolve, 5000)); // Parameters for checking the status of the transaction const getStatusParams = { transactionId: txHash, requestId: requestId, integratorId: integratorId, quoteId: quoteId, // Required for Squid Intents transactions }; const completedStatuses = ["success", "partial_success", "needs_gas", "not_found"]; const maxRetries = 10; // Maximum number of retries for status check let retryCount = 0; // Get the initial status let status = await squid.getStatus(getStatusParams); console.log(`Initial route status: ${status.squidTransactionStatus}`); // Loop to check the transaction status until it is completed or max retries are reached do { try { // Wait a few seconds before checking the status await new Promise((resolve) => setTimeout(resolve, 5000)); // Retrieve the transaction's route status status = await squid.getStatus(getStatusParams); // Display the route status console.log(`Route status: ${status.squidTransactionStatus}`); } catch (error: unknown) { // Handle error if the transaction status is not found if (error instanceof Error && (error as any).response && (error as any).response.status === 404) { retryCount++; if (retryCount >= maxRetries) { console.error("Max retries reached. Transaction not found."); break; } console.log("Transaction not found. Retrying..."); continue; } else { throw error; } } } while (status && !completedStatuses.includes(status.squidTransactionStatus)); // Wait for the transaction to be executed console.log("Swap transaction executed:", txHash); })(); ``` # Cross-chain NFT Purchase Example This example walks you through how to implement the SDK to purchase an NFT on any chain. Download the full example [**here**](https://github.com/0xsquid/examples/blob/main/V2/sdk/oldExamples/buyNftFromAnyChain/src/index.ts)**.** ```typescript import { Squid } from "@0xsquid/sdk"; import { ethers } from "ethers"; // Environment // add to a file named ".env" to prevent them being uploaded to github import * as dotenv from "dotenv"; dotenv.config(); const avaxRpcEndpoint = process.env.AVAX_RPC_ENDPOINT; const privateKey = process.env.PRIVATE_KEY; // ABIs import erc1155Abi from "../abi/erc1155Abi"; import erc20Abi from "../abi/erc20Abi"; import treasureMarketplaceAbi from "../abi/treasureMarketplaceAbi"; // Squid call types for multicall const SquidCallType = { DEFAULT: 0, FULL_TOKEN_BALANCE: 1, FULL_NATIVE_BALANCE: 2, COLLECT_TOKEN_BALANCE: 3, }; // addresses and IDs const avalancheId = 43114; const arbitrumId = 42161; const nativeToken = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE"; const squidMulticall = "0x4fd39C9E151e50580779bd04B1f7eCc310079fd3"; const magicToken = "0x539bdE0d7Dbd336b79148AA742883198BBF60342"; const treasureAddress = "0x09986b4e255b3c548041a30a2ee312fe176731c2"; // treasure contract const moonrockNftAddress = "0xc5295c6a183f29b7c962df076819d44e0076860e"; const moonrockOwner = "0xa5c53eb116EC0CE355D8be38b0EB424ce520A4db"; // amount of AVAX to send (currently 0.05 AVAX) const amount = "30000000000000000"; const getSDK = () => { const squid = new Squid({ baseUrl: "https://v2.api.squidrouter.com", integratorId: process.env.INTEGRATOR_ID, }); return squid; }; (async () => { // set up your RPC provider and signer const provider = new ethers.JsonRpcProvider(avaxRpcEndpoint); const signer = new ethers.Wallet(privateKey, provider); console.log("Signer address: ", signer.address); // instantiate the SDK const squid = getSDK(); // init the SDK await squid.init(); console.log("Squid inited"); // Generate the encoded data to approve the Treasure contract to spend Magic const erc20ContractInterface = new ethers.Interface(erc20Abi); const approveEncodeData = erc20ContractInterface.encodeFunctionData( "approve", [treasureAddress, "0"] ); // Generate the encoded data to buy the NFT on Treasure // This example buys a MoonRock NFT on Treasure on mainnet // https://trove.treasure.lol/collection/smol-treasures/1 const treasureMarketplaceInterface = new ethers.Interface( treasureMarketplaceAbi ); const _buyItemParams = { nftAddress: moonrockNftAddress, tokenId: 1, owner: moonrockOwner, quantity: 1, maxPricePerItem: "990000000000000000", paymentToken: magicToken, usinEth: false, }; const buyMoonRockNftEncodeData = treasureMarketplaceInterface.encodeFunctionData("buyItems", [ [_buyItemParams], ]); // Generate the encoded data to transfer the NFT to signer's address const erc1155Interface = new ethers.Interface(erc1155Abi); const transferNftEncodeData = erc1155Interface.encodeFunctionData( "safeTransferFrom", [squidMulticall, signer.address, 1, 1, 0x00] ); // Generate the encoded data to send any remaining Magic back to signer's address const transferMagicEncodeData = erc20ContractInterface.encodeFunctionData( "transfer", [signer.address, "0"] ); const { route, requestId } = await squid.getRoute({ toAddress: signer.address, fromChain: avalancheId, fromToken: nativeToken, fromAmount: amount, toChain: arbitrumId, toToken: magicToken, slippage: 1, //optional, Squid will dynamically calculate if removed // enableExpress: false, // default is true on all chains except Ethereum postHook: [ description: "Buy Milady 2039 on Ethereum" { callType: SquidCallType.FULL_TOKEN_BALANCE, target: magicToken, value: "0", callData: approveEncodeData, payload: { tokenAddress: magicToken, inputPos: 1, }, estimatedGas: "50000", }, { callType: SquidCallType.DEFAULT, target: treasureAddress, value: "0", callData: buyMoonRockNftEncodeData, payload: { tokenAddress: "1", inputPos: 1, }, estimatedGas: "80000", }, { callType: SquidCallType.DEFAULT, target: moonrockNftAddress, value: "0", callData: transferNftEncodeData, payload: { tokenAddress: "0x", inputPos: 1, }, estimatedGas: "50000", }, { callType: SquidCallType.FULL_TOKEN_BALANCE, // transfer any remaining MAGIC to the user's account target: magicToken, value: "0", callData: transferMagicEncodeData, payload: { tokenAddress: magicToken, inputPos: 1, }, estimatedGas: "50000", }, ], }); const quoteId = route.quoteId; // Save quoteId — required for Squid Intents status tracking console.log("quoteId:", quoteId); const tx = (await squid.executeRoute({ signer, route, })) as unknown as ethers.TransactionResponse; const txReceipt = await tx.wait(); const axelarScanLink = "https://axelarscan.io/gmp/" + txReceipt.hash; console.log( "Finished! Please check Axelarscan for more details: ", axelarScanLink, "\n" ); console.log( "Track status via API call to: https://api.squidrouter.com/v1/status?transactionId=" + txReceipt.hash, "\n" ); // It's best to wait a few seconds before checking the status await new Promise((resolve) => setTimeout(resolve, 5000)); const status = await squid.getStatus({ transactionId: txReceipt.hash, requestId: requestId, integratorId: process.env.INTEGRATOR_ID, quoteId: quoteId, // Required for Squid Intents transactions }); console.log("Status: ", status); })(); ``` # Get Route Status This method aims to provide the status of the transaction ## Get Route Status Squid provides a status of cross-chain transactions. You can access this status using the `getStatus` method on our SDK. You can also check completion of most cross chain transactions on Squid by copying the transaction hash into [SquidScan](https://scan.squidrouter.com/). Note, for some Cosmos transactions and others in the future this will not work. ### Usage ```typescript const status = await squid.getStatus({ transactionId, requestId, // optional integratorId, // optional quoteId, // Required for Squid Intents transactions bridgeType, // optional }) ``` ### Request Parameters | Parameter | Type | Required | Description | | --------------- | ------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | `transactionId` | string | Yes | The transaction hash | | `quoteId` | string | Yes | The quote ID from the route response. Required for Squid Intents status tracking. Also enables volume and token activity sharing with integrators. | | `requestId` | string | No | The request ID (legacy parameter) | | `integratorId` | string | No | Your integrator ID | | `bridgeType` | string | No | The bridge type (e.g., `chainflip`, `chainflipmultihop` for BTC/SOL transactions) | #### Getting Quote ID from Route Response The `quoteId` can be found at the top level of the route response. Including this parameter in status requests will enable volume and specific token activity sharing with integrators in the near future: ```json { "route": { "quoteId": "6f388be5205ee044cd7fd5047a4ce72e" } } ``` ### Understanding squidTransactionStatus The most important response param is `squidTransactionStatus`. This param will tell you what to show the user. There are 6 possible states: ```typescript { SUCCESS = "success", NEEDS_GAS = "needs_gas", ONGOING = "ongoing", PARTIAL_SUCCESS = "partial_success", NOT_FOUND = "not_found", REFUND = "refund" } ``` #### SUCCESS This indicates the transaction has completed on all chains. Whether a single chain, 2 chain or 3 chain call, the swap, stake, NFT purchase, bridge etc. has compl
프로젝트로 돌아가기