Squid 백서

Squid

원문

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

series of contract interactions like staking, minting, or withdrawing and on either the source chain(the are executing the transaction from) or the destination chain(the chain that they are receiving bridged assets on). <figure><img src="https://4247625265-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FtXbXyuWIO2PwzNc5Dets%2Fuploads%2FQhiPjgwx54luyTD06fJo%2Fhooks3.png?alt=media&amp;token=6af2f05f-6d6c-411c-8973-ecaaf19bba24" alt=""><figcaption></figcaption></figure> ### **Key Benefits** * **Automation:** Both preHooks and postHooks automate repetitive and necessary tasks, reducing manual intervention and the potential for errors. * **Efficiency:** By handling preparatory and follow-up actions automatically, preHooks and postHooks streamline the transaction process, improving efficiency and user satisfaction. * **Flexibility:** Developers can customize workflows to meet specific needs, such as integrating additional checks, swaps, or minting processes tailored to their applications. ### **Examples** Squid's hooks are what makes it possible to do *anything* across chain. * Buy or mint an NFT after a bridging assets * Cross-chain swap then stake the assets * Unstake assets then perform a cross-chain swap * Performa cross-chain swap and then deposit into an exchange # How do hooks work Squid's hooks are powered by the [Squid Multicall contract.](https://docs.squidrouter.com/additional-resources/contracts) An arbitrary number of calls can be executed before or after a swap or bridge. <figure><img src="https://4247625265-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FtXbXyuWIO2PwzNc5Dets%2Fuploads%2FpS0pQgNPwLf2aWxs8hed%2FhooksFlow2.png?alt=media&amp;token=89511cda-9647-4e4f-b89b-ca494ba34de1" alt=""><figcaption></figcaption></figure> Note that hooks can be executed before or after a single chain swap too. <figure><img src="https://4247625265-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FtXbXyuWIO2PwzNc5Dets%2Fuploads%2FXj97gi6jgdmxY4uAw99T%2FhooksFlow.png?alt=media&amp;token=ffa3dfc8-0f56-4a4c-a153-9411c5e26b44" alt=""><figcaption></figcaption></figure> # Build a preHook `preHooks` are executed on the Squid Multicall contract on the `fromChain` before any swaps or bridging has occurred. After `preHooks`, the full balance on the Multicall will be swapped or bridged across chains. The `fromToken` and `fromAmount` in your route request should be the amount of tokens you expect to on the Multicall after the `preHooks` are executed. The snippet example below illustrates wrapping ETH on Arbitrum then bridging to Binance Smart Chain using both our API and SDK. {% tabs %} {% tab title="SDK" %} To try the full working SDK preHook example, visit our [SDK Examples Repository](https://github.com/0xsquid/examples/tree/main/V2/sdk). <pre class="language-typescript"><code class="lang-typescript"> //import Squid SDK and types import { Squid } from "@0xsquid/sdk"; import { ChainType, EvmContractCall } from "@0xsquid/squid-types"; <strong>// Import WETH ABI </strong>import wethAbi from "../abi/wethAbi"; // Adjust the path if necessary // Function to get Squid SDK instance const getSDK = (): Squid => { const squid = new Squid({ baseUrl: "https://v2.api.squidrouter.com", integratorId: integratorId, }); return squid; }; // Main function (async () => { // Initialize Squid SDK const squid = getSDK(); await squid.init(); console.log("Initialized Squid SDK"); // Creating Contract interfaces const wethInterface = new ethers.utils.Interface(wethAbi); const wrapEncodedData = wethInterface.encodeFunctionData("deposit"); // Set up parameters for wrapping ETH to wETH and bridging to BUSD on Binance Smart Chain const params = { fromAddress: signer.address, fromChain: fromChainId, fromToken: WETH_ADDRESS, // WETH on Arbitrum fromAmount: amount.toString(), toChain: toChainId, toToken: toToken, toAddress: signer.address, slippage: 1, preHook: { chainType: ChainType.EVM, fundAmount: amount.toString(), fundToken: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", // Native ETH <strong> calls: [ </strong> { chainType: ChainType.EVM, callType: 2, // 2 corresponds to CALL_DATA target: WETH_ADDRESS, value: amount.toString(), // Amount of ETH to wrap callData: wrapEncodedData, payload: { tokenAddress: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", // Native ETH inputPos: 0, }, estimatedGas: "500000", } as EvmContractCall, ], provider: "Integration Test", //This should be the name of your product or application that is triggering the hook description: "Wrap native ETH", logoURI: "https://pbs.twimg.com/profile_images/1548647667135291394/W2WOtKUq_400x400.jpg", //Add your logo here }, }; console.log("Parameters:", params); // Get the swap route using Squid SDK const { route, requestId } = await squid.getRoute(params); console.log("Calculated route:", route.estimate.toAmount); </code></pre> {% endtab %} {% tab title="API" %} To try the full working API preHook example, visit our [API Examples Repository](https://github.com/0xsquid/examples/tree/main/V2/api). ```typescript // Import WETH ABI import wethAbi from "../abi/wethAbi"; // Adjust the path if necessary // Creating Contract interfaces const wethContract = new ethers.Contract(WETH_ADDRESS, wethAbi, signer); // Set up parameters for wrapping ETH to wETH and bridging to BUSD on Binance Smart Chain (async () => { const params = { fromAddress: signer.address, fromChain: fromChainId, fromToken: WETH_ADDRESS, // WETH on Arbitrum fromAmount: amount.toString(), toChain: toChainId, toToken: toToken, toAddress: signer.address, preHook: { chainType: "evm", fundAmount: amount.toString(), fundToken: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", // Native ETH provider: "Integration Test", description: "Wrap native ETH", logoURI: "http://", calls: [ { chainType: "evm", callType: 2, target: WETH_ADDRESS, value: "0", callData: wethContract.interface.encodeFunctionData("deposit"), // Function signature for deposit() in WETH contract payload: { tokenAddress: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", // Native ETH inputPos: 0, }, estimatedGas: "500000", }, ], }, }; console.log("Parameters:", params); ``` {% endtab %} {% endtabs %} # Build a postHook After the swap or bridge is executed, the resulting tokens will be left on the Squid Multicall contract. From there the `postHooks` calls will be executed. {% tabs %} {% tab title="SDK" %} Create contract interfaces for the posthook ```typescript // Creating Contract interfaces // Approve the lending contract to spend the erc20 const erc20Interface = new ethers.utils.Interface(erc20Abi); const approvalerc20 = erc20Interface.encodeFunctionData("approve", [ radiantLendingPoolAddress, ethers.constants.MaxUint256, ]); // Create contract interface and encode deposit function for Radiant lending pool const radiantLendingPoolInterface = new ethers.utils.Interface( radiantLendingPoolAbi ); const depositEncodedData = radiantLendingPoolInterface.encodeFunctionData( "deposit", [ usdcArbitrumAddress, "0", // Placeholder for dynamic balance signer.address, 0, ] ); ``` Create postHook ```typescript // Set up parameters for swapping tokens and depositing into Radiant lending pool const params = { fromAddress: signer.address, fromChain: fromChainId, fromToken: fromToken, fromAmount: amount, toChain: toChainId, toToken: usdcArbitrumAddress, toAddress: signer.address, slippage: 1, 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: approvalerc20, payload: { tokenAddress: usdcArbitrumAddress, inputPos: 1, }, estimatedGas: "50000", }, { chainType: ChainType.EVM, callType: 1, // SquidCallType.FULL_TOKEN_BALANCE target: radiantLendingPoolAddress, value: "0", callData: depositEncodedData, payload: { tokenAddress: usdcArbitrumAddress, inputPos: 1, }, estimatedGas: "50000", }, ], provider: "Integration Test", //This should be the name of your product or application that is triggering the hook description: "Wrap native ETH", logoURI: "https://pbs.twimg.com/profile_images/1548647667135291394/W2WOtKUq_400x400.jpg", //Add your logo here }, }; ``` {% endtab %} {% tab title="API" %} Import the ABIs and create the contract interface ```typescript // Import Radiant lending pool ABI import radiantLendingPoolAbi from "../abi/radiantLendingPoolAbi"; // Import erc20 contract ABI import erc20Abi from "../abi/erc20Abi"; // Set up JSON RPC provider and signer const provider = new ethers.providers.JsonRpcProvider(FROM_CHAIN_RPC); const signer = new ethers.Wallet(privateKey, provider); // Creating Contract interfaces // Approve the lending contract to spend the erc20 const erc20Interface = new ethers.utils.Interface(erc20Abi); const approvalerc20 = erc20Interface.encodeFunctionData("approve", [ radiantLendingPoolAddress, ethers.constants.MaxUint256, ]); // Create contract interface and encode deposit function for Radiant lending pool const radiantLendingPoolInterface = new ethers.utils.Interface( radiantLendingPoolAbi ); const depositEncodedData = radiantLendingPoolInterface.encodeFunctionData( "deposit", [ usdcArbitrumAddress, "0", // Placeholder for dynamic balance signer.address, 0, ] ); ``` Build the parameters to including the postHook <pre class="language-typescript"><code class="lang-typescript"> <strong>params = { </strong> fromAddress: signer.address, fromChain: fromChainId, fromToken: fromToken, fromAmount: amount, toChain: toChainId, toToken: usdcArbitrumAddress, toAddress: signer.address, slippage: 1, postHook: { chainType: "evm", //fundAmount: amount, //only required for prehooks //fundToken: usdcArbitrumAddress, //only required for prehooks calls: [ { callType: 1, target: usdcArbitrumAddress, value: "0", // this will be replaced by the full native balance of the multicall after the swap callData: approvalerc20, payload: { tokenAddress: usdcArbitrumAddress, // unused in callType 2, dummy value inputPos: "1", // unused }, estimatedGas: "50000", chainType: "evm", }, { callType: 1, // SquidCallType.FULL_TOKEN_BALANCE target: radiantLendingPoolAddress, value: "0", callData: depositEncodedData, payload: { tokenAddress: usdcArbitrumAddress, inputPos: "1", }, estimatedGas: "50000", chainType: "evm", }, ], description: "", }, }; </code></pre> {% endtab %} {% endtabs %} # Using the full ERC20 or Native balance in a call The Squid Multicall can update the value of a param on-chain before or after the Swap or bridge has occurred. This lets you do the following: * Send the remainder of tokens to the user's address, after minting or buying something at a fixed price * Stake the full amount received from a swap * Unstake, then swap the full amount across chains This is designated by using `callType` ```typescript export enum SquidCallType { DEFAULT = 0, FULL_TOKEN_BALANCE = 1, FULL_NATIVE_BALANCE = 2, COLLECT_TOKEN_BALANCE = 3, // unused in hooks } ``` {% tabs %} {% tab title="FULL\_ERC20\_BALANCE" %} ```typescript const sendRemainderToUserCall = { 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", }, ``` {% endtab %} {% tab title="FULL\_NATIVE\_BALANCE" %} ```typescript const mintLoanWithFullNativeBalanceCall = { callType: SquidCallType.FULL_NATIVE_BALANCE, target: moonwellGlmrAddress, value: "0", // this will be replaced by the full native balance of the multicall after the swap callData: mintEncodeData, payload: { tokenAddress: "0x", // unused in callType 2, dummy value inputPos: 1, // unused }, estimatedGas: "250000", }, ``` {% endtab %} {% tab title="DEFAULT" %} ```typescript const repayLoanCall = { callType: SquidCallType.DEFAULT, 0 target: aavePoolAddress, value: '0', callData: repayEncodedData, estimatedGas: '50000', payload: { tokenAddress: "", // unused in callType 0, dummy value inputPos: 0, // unused in callType 0, dummy value } ``` {% endtab %} {% endtabs %} # Transfer the remainder to the user Always remember to transfer all tokens left over from the swap or from your calls to the user's address, or your own contract address, at the end of the postHooks. If you don't do this, there will likely be some funds left on the Squid Multicall Contract after your transaction has completed. The best way to do this is to add a call sending the full ERC20 or NATIVE balance of the multicall to the address desired. [Using the full ERC20 or Native balance in a call](/old-v2-documentation-deprecated/key-concepts/hooks/using-the-full-erc20-or-native-balance-in-a-call) # Get a route and execute as normal From here on, there is no change needed in your flow ✅ Continue: [Execute the route](/old-v2-documentation-deprecated/key-concepts/execute-the-route) # Track status Our status API returns the status of a cross chain transaction. The response param `status.squidTransactionStatus` tells the user what they need to do next. {% hint style="danger" %} **Squid Intents Transactions**: Status polling is **required** for Squid Intents. After executing a Squid Intents transaction, you **must** call the status API with the `quoteId` parameter. If `quoteId` is not included in the status call, the Squid Intents transaction will be **refunded** to the source chain. See [Integrating Squid Intents](/api-and-sdk-integration/coral-intent-swaps/integrating-squid-intents) for details. {% endhint %} ### API Endpoint ``` GET https://v2.api.squidrouter.com/v2/status ``` #### Parameters | Parameter | Type | Required | Description | | --------------- | ------ | -------- | ------------------------------------- | | `transactionId` | string | Yes | The transaction hash | | `quoteId` | string | Yes | The quote ID from the route response. | | `fromChainId` | string | Yes | The source chain ID | | `toChainId` | string | Yes | The destination chain ID | | `requestId` | string | No | The request ID (legacy parameter) | #### Example Request ``` /v2/status?transactionId=40E494A80393963DBC2D493E3EB6E39B7C48810CD345BF0FA8E48683B9841C43&fromChainId=cosmoshub-4&toChainId=osmosis-1&quoteId=27232c0b82fa6661b2799894bd0da80c ``` ### Code Examples #### 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" } } ``` #### Updated SDK Interface ```typescript interface StatusParams { transactionId: string; requestId?: string; integratorId?: string; quoteId?: string; } ``` #### Function to Get Transaction Status ```javascript // Function to get the status of the transaction using Squid API const getStatus = async (params: any) => { try { const result = await axios.get("https://v2.api.squidrouter.com/v2/status", { params: { transactionId: params.transactionId, requestId: params.requestId, fromChainId: params.fromChainId, toChainId: params.toChainId, quoteId: params.quoteId, // Required for Squid Intents transactions }, headers: { "x-integrator-id": integratorId, }, }); return result.data; } catch (error) { if (error.response) { console.error("API error:", error.response.data); } console.error("Error with parameters:", params); throw error; } }; ``` #### Polling for Transaction Status ```javascript // Function to periodically check the transaction status until it completes const updateTransactionStatus = async (txHash: string, requestId?: string, quoteId?: string) => { const getStatusParams = { transactionId: txHash, requestId: requestId, fromChainId: fromChainId, toChainId: toChainId, quoteId: quoteId, // Required for Squid Intents transactions }; let status; const completedStatuses = ["success", "partial_success", "needs_gas", "not_found", "refund_status"]; const maxRetries = 10; // Maximum number of retries for status check let retryCount = 0; do { try { status = await getStatus(getStatusParams); console.log(`Route status: ${status.squidTransactionStatus}`); } catch (error) { if (error.response && error.response.status === 404) { retryCount++; if (retryCount >= maxRetries) { console.error("Max retries reached. Transaction not found."); break; } console.log("Transaction not found. Retrying..."); await new Promise((resolve) => setTimeout(resolve, 5000)); // Wait for 5 seconds before retrying continue; } else { throw error; // Rethrow other errors } } if (!completedStatuses.includes(status.squidTransactionStatus)) { await new Promise((resolve) => setTimeout(resolve, 5000)); // Wait for 5 seconds before checking the status again } } while (!completedStatuses.includes(status.squidTransactionStatus)); }; ``` ### Understanding 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_STATUS = "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 completed without any reversions and the user has received the intended funds. #### NEEDS\_GAS This state is specific for Axelar transactions. If the gas price has spiked on the destination chain and execution cannot complete, Squid will return this status. The best user flow in this case is to send the user to Axelarscan to view the paused transaction. #### ONGOING There is nothing wrong, nothing to do, just relax and wait. The transaction should have an `estimatedRouteDuration` in seconds that you can read from the `/route` response. We generally recommend contacting support after either 15 minutes has passed, or double the `estimatedRouteDuration`, whichever is larger. #### PARTIAL\_SUCCESS This status indicates that the transaction has completed some of its steps. Currently, there is only one case that could cause this state. In the future there will be many, but we will provide more metadata around the `PARTIAL_SUCCESS`. For now, this is what has happened: * The source chain transaction successfully executed, along with any swaps or contract calls. * The destination chain transaction has executed, but reverted during execution. This is usually due to slippage on volatile assets, but if you are trying to buy an NFT or do some cross-chain staking, then it could indicate that the custom hook had a failure. **What token do I receive when a swap fails?** The token you receive depends on the route type: | Route Type | Failure Behavior | Token Received | | ----------------- | ---------------------- | -------------------------------------------------------------------------------------------------- | | **Axelar** | Destination swap fails | **axlUSDC** on the **destination chain** | | **Squid Intents** | Swap fails | **RFQ bridge token** (typically the chain's native asset or USDC) refunded on the **source chain** | {% hint style="info" %} For Axelar routes, you will receive axlUSDC in your destination wallet. For Squid Intents routes, the funds are refunded to your source address — see the REFUND status below. {% endhint %} #### NOT\_FOUND The Squid API cannot find an on-chain record of the transaction. This is usually due to our various services or service providers not having indexed the completed transaction. This state i
프로젝트로 돌아가기