Squid 백서

Squid

원문

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

cute yourself, manually. You can get all the data needed for execution from `route.transactionRequest` . Including calldata, target address, value to send and gas recommendations. {% endtab %} {% tab title="API" %} ```typescript const transactionRequest = route.transactionRequest; // Execute the swap transaction const contract = new ethers.Contract( transactionRequest.targetAddress, [], signer ); const tx = await contract.send(transactionRequest.data, { value: transactionRequest.value, gasPrice: await provider.getGasPrice(), gasLimit: transactionRequest.gasLimit, }); const txReceipt = await tx.wait(); ``` {% endtab %} {% tab title="Widgets" %} All widgets allow the user to submit once they have entered all required inputs and connected their wallet(s). All routes require gas in the user's account on source chain only. The widgets will show a warning when the amount of gas needed is higher than their balance. {% endtab %} {% endtabs %} # Hooks Squid is a transaction bundler at heart. Squid's hooks enable users to sign one transaction and that transaction handles a 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://etherscan.io/address/0x4fd39C9E151e50580779bd04B1f7eCc310079fd3) 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 `postHook` 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) # Add your hooks to a route request, or widget ```typescript const params = { fromAddress: signer.address, fromChain: ethereumId, fromToken: repayAsset, fromAmount: repayAmount, toChain: binanceSmartChainId, toToken: nativeToken, toAddress: binanceAddress, slippage: 1, quoteOnly: false, preHook: preHook, postHook: postHook, }; ``` # 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) # Boost Boost is what makes Squid so fast. It is an intent-like model which brings transaction times down to less than 20 seconds in all cases. Boost is a smart contract overlay which allows a provider to optimistically fulfill a transaction immediately after the user completes their transaction on the source chain. The provider is providing a short term loan, which is guaranteed by the pending bridge transaction. Boost can be used with any Squid feature, including hooks, fees, gas on destination, etc. <figure><img src="https://4247625265-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FtXbXyuWIO2PwzNc5Dets%2Fuploads%2FBCY4VYjI4upCYrQkCzDy%2FBoost%20flow.png?alt=media&amp;token=cdc864f5-c171-4842-8cb1-3e52253ea80f" alt=""><figcaption></figcaption></figure> # 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. {% tabs %} {% tab title="SDK" %} ```typescript // Wait a few seconds before checking the status await new Promise((resolve) => setTimeout(resolve, 5000)); // Retrieve the transaction's route status const getStatusParams = { transactionId: txReceipt.transactionHash, requestId: requestId, integratorId: integratorId, fromChainId: polygonId, toChainId: arbitrumId, }; const status = await squid.getStatus(getStatusParams); // Display the route status console.log(`Route status: ${status.squidTransactionStatus}`); ``` {% endtab %} {% tab title="API" %} ```typescript const getStatus = async () => { const result = await axios.post('https://v2.api.squidrouter.com/v2/status', { headers: { 'x-integrator-id': integratorId, }, { transactionId, requestId, // get this from your route response fromChainId, toChainId } }); return result.data; }; // access result.data.squidTransactionStatus ``` {% endtab %} {% tab title="Widgets" %} There is a common status flow for all widgets. There are views which correspond to each possible state of `status.squidTransactionResponse` as returned by the Squid API. The widgets will regularly call for status or on refocus of a window. Status of historical states can be seen in the *Transaction history* page. {% endtab %} {% endtabs %} ### Understanding squidTransactionStatus This param will tell you what to show the user. There are 5 possible states: ```typescript { SUCCESS = "success", NEEDS_GAS = "needs_gas", ONGOING = "ongoing", PARTIAL_SUCCESS = "partial_success", NOT_FOUND = "not_found" } ``` 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. * If there is a partial success, the user will have received the bridged token in their wallet on the destination chain. In most cases this is axlUSDC. 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 is often returned for 5-10 seconds after the transaction was executed, while chain indexing occurs. This should not persist after maximum a few minutes (some chains such as Filecoin take a very long time to index, and for block inclusion). If it does, then get in touch with us on [Discord](https://discord.gg/squidrouter). # Types We recommend using the types from our npm package. If you are using our API without our SDK, you can find the types inside `node_modules/@0xsquid/sdk/dist/types/index.d.ts` after [Broken mention](broken://pages/pQzBnlnLhbC4MQnwWa7c) ```typescript import { Token, ChainData } from '@0xsquid/sdk/dist/types' ``` # Collect Fees ### Integrator Fee Structure Squid v2 allows integrators to implement their own fee structure on top of Squid's platform fees. This document details the structure of Integrator fees implemented on through Squid. **To implement fees please contact the Squid team
프로젝트로 돌아가기