Squid 백서

Squid

원문

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

or swap has completed. * Configure the destination token needed to swap/deposit or stake. * Configure the contract calls (hooks) to be made on the destination token. (stake, lend, deposit etc) Installation is easy, and should take 30min-3 hours depending on the complexity of your staking or deposit function calls. # Installing the Widget Preparing to integrate the widget into your app If you have any questions along the way, please contact us on our [Discord](https://discord.com/invite/squidrouter) in the ***⛓│developers*****&#x20;channel**. ### Installation {% hint style="info" %} Squid issues Integrator IDs on a limited basis upon review. To use the staking widget, please [submit a partnership request](https://squidrouter.typeform.com/partnerships) to acquire an ID. {% endhint %} ```tsx < SquidStakingWidget config={{ integratorId: "<partner-id>", // ... Other config options, such as theme, titles, etc. }} /> ``` `integratorId` is required for Squid integrations. Submit a [partnership request](https://squidrouter.typeform.com/partnerships) to request an Integrator ID. Install the Squid Widget npm package: ``` npm i @0xsquid/staking-widget ``` or ``` yarn add @0xsquid/staking-widget ``` # Configuration Staking widget configuration The configuration of this widget is almost the same as the Swap widget. Take a look at these docs: * [Customization Guide](/old-v2-documentation-deprecated/add-a-widget/widget/customization-guide) * [Theme Customization](/old-v2-documentation-deprecated/add-a-widget/widget/customization-guide/theme-customization) In addtion to the standard widget config, the staking widget requires a `stakeConfig`. ### Working example {% @github-files/github-code-block url="<https://github.com/0xsquid/widget-integrations/blob/main/packages/next-app/pages/staking.tsx>" %} ### Adding the Staking transactions Basically the stakeConfig is here to tell the widget what happens after the cross chain swap. *Here's an example flow:* * User wants to stake USDC on Moonbeam from BNB on Binance * Normal cross chain swap happens with Squid (swap to axlUSDC, bridge, swap to destination token, configured by the developer) * Now it's time to execute customContractCalls: * Give approval to SquidMultiCall to send dest token (let's say GLMR received earlier) * Effectively stake this amount on Moonbeam * Send staked token to user The main attribute to update is `customContractCalls`. You can read more about the configuration of customContractCalls here: [Hooks](/api-and-sdk-integration/key-concepts/hooks) ### stakeConfig structure ```typescript export interface StakeConfig { // TokenData will have all informations about the stakedToken, // such as symbol, image, name, chainId, etc) stakedToken: TokenData; // This method will be used to compute the exchange rate between the staked token and the token to stake // Basically a multiplier from 0 to x // Then if the amount that the route gets is 100, and the exchange rate is 0.5, we'll show 50 as the amount to be received for stakedToken // If nothing is specified, the exchange rate will be 1 stakedTokenExchangeRateGetter?: () => Promise<number>; // At the moment we cannot unstake directly through the widget, // If you want to tell the user that he can unstake, we'll display a link for this unstakeLink?: string; // Intro page is optional, it will display a page before proposing to swap, // This can be useful for the user to understand what will be possible introPage?: { title: string; logoUrl: string; stakingContract?: { address: string; explorerLink?: string; }; }; // This is mandatory, and different from stakedToken // This token won't be displayed but will be used to stake // Route will be like this: // - User selects BNB on Binance // - We swap this to axlUSDC using Axelar // - axlUSDC is bridged to the chainId of token below // - axlUSDC is swapped to token below tokenToStake: { chainId: number | string; address: string; }; // After swap/bridge is done, custom contract call can be executed // For example staking the "tokenToStake" into "stakedToken" customContractCalls: (Omit<ContractCall, "callData"> & { callData?: (routeVariables: CallDataGetter) => string; })[]; } ``` # Importing The widget Install dependencies: ```bash npm i @0xsquid/staking-widget @0xsquid/sdk ethers ``` And import the widget in your app: ```typescript import { SquidStakingWidget } from "@0xsquid/staking-widget"; import { SquidCallType } from "@0xsquid/sdk"; import { ethers } from "ethers"; import erc20Abi from "./abi/erc20Abi"; import pinjamStakingPoolAbi from "./abi/pinjamStakingPoolAbi"; const pinjamStakingPoolInterface = new ethers.Interface( pinjamStakingPoolAbi ); const kavaId = 2222; const pinjamAxlUsdcPoolAddress = "0x11c3d91259b1c2bd804344355c6a255001f7ba1e"; const axlUsdcKavaAddress = "0xeb466342c4d449bc9f53a865d5cb90586f405215"; const pAxlUsdcAddress = "0x5c91f5d2b7046a138c7d1775bffea68d5e95d68d"; const erc20Interface = new ethers.Interface(erc20Abi); export default function App() { const stakeConfig = { tokensConfig: [ { stakedTokenExchangeRateGetter: async () => { return 1; }, unstakeLink: "https://app.pinjamlabs.com/staking", customContractCalls: [ { callType: SquidCallType.FULL_TOKEN_BALANCE, target: axlUsdcKavaAddress, value: "0", callData: () => { return erc20Interface.encodeFunctionData("approve", [ pinjamAxlUsdcPoolAddress, "0", ]); }, payload: { tokenAddress: axlUsdcKavaAddress, inputPos: 1, }, estimatedGas: "50000", }, { callType: SquidCallType.FULL_TOKEN_BALANCE, target: pinjamAxlUsdcPoolAddress, value: "0", callData: (route: any) => { if (route.destinationAddress) { return pinjamStakingPoolInterface.encodeFunctionData( "deposit", [axlUsdcKavaAddress, "0", route.destinationAddress, true] ); } return "0x0000000000000000000000000000000000000000"; }, payload: { tokenAddress: axlUsdcKavaAddress, inputPos: 1, }, estimatedGas: "250000", }, ], stakedToken: { chainId: kavaId, address: pAxlUsdcAddress, name: "paxlUSDC", symbol: "paxlUSDC", decimals: 6, logoURI: "https://assets.coingecko.com/coins/images/6319/thumb/USD_Coin_icon.png?1547042389", coingeckoId: "usd-coin", }, tokenToStake: { chainId: kavaId, address: axlUsdcKavaAddress, }, stakingContract: { address: "0xe5274e38e91b615d8822e8512a29a16ff1b9c4af", explorerLink: "https://kava.mintscan.io/account/", }, logoUrl: "https://app.pinjamlabs.com/icons/pinkav.svg", }, ], introPage: { title: "Stake paxlUSDC on Kava", description: "Stake paxlUSDC on Kava to earn rewards", }, }; return ( <SquidStakingWidget config={{ apiUrl: "https://v2.api.squidrouter.com", integratorId: "<your integrator id>", stakeConfig, }} /> ); } ``` # API ## Overview Squid API is for devs using a client other than javascript. The API offers nearly the full functionality of the SDK, and is only missing some helper functions for front end work. ### Base URL All API endpoints use the following base URL: ``` https://v2.api.squidrouter.com/v2/ ``` ### Squid Intents (Enabled by Default) Squid Intents is **enabled by default** on all integrations. When a Squid Intents route is used, you **must** pass the `quoteId` in the status call for the transaction to be executed successfully. Failing to poll status with the `quoteId` will cause the transaction to fail. {% hint style="danger" %} After executing a Squid Intents transaction, you **must** call the status API with the `quoteId` parameter. See [Track Status](/api-and-sdk-integration/key-concepts/track-status) for details. {% endhint %} Below is the most basic example of building with Squid, a cross-chain swap. In this example, we will cover the key concepts involved in the swap. To find all examples, please visit our [examples repo](https://github.com/0xsquid/examples). ## Getting Started: Cross-chain Swaps This example walks through the index.js code included in the [**EVMtoEVM API swap example**](https://github.com/0xsquid/examples/tree/main/V2/api/evmToEVMSwap)**.** Once you download the example folder [**evmToEVMSwap**](https://github.com/0xsquid/examples/tree/main/V2/api/evmToEVMSwap) **u**se the `yarn install` to install the necessary packages and create a .env file modeled based off the `.env.example` folder. **The following actions take place in the index.js:** * Loading necessary packages and environmental variables * Defining route parameters, RPC provider, and wallet signer * Creating the route request and the transaction status functions * Defining the route parameters and requesting the route * Executing the route transactions * Checking the status of the transactions ```typescript import { ethers } from "ethers"; import axios from "axios"; 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.FROM_CHAIN_RPC_ENDPOINT!; // Define chain and token addresses const fromChainId = "56"; // BNB const toChainId = "42161"; // Arbitrum const fromToken = "0x55d398326f99059fF775485246999027B3197955"; // USDT const toToken = "0xaf88d065e77c8cC2239327C5EDb3A432268e5831"; // USDC // Define the amount to be sent const amount = "1000000000000000"; // Set up JSON RPC provider and signer const provider = new ethers.providers.JsonRpcProvider(FROM_CHAIN_RPC); const signer = new ethers.Wallet(privateKey, provider); // Function to get the optimal route for the swap using Squid API 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"]; // Retrieve request ID from response headers return { data: result.data, requestId: requestId }; } catch (error) { if (error.response) { console.error("API error:", error.response.data); } console.error("Error with parameters:", params); throw error; } }; // 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; } }; // 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"]; 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)); }; // Set up parameters for swapping tokens (async () => { const params = { fromAddress: signer.address, fromChain: fromChainId, fromToken: fromToken, fromAmount: amount, toChain: toChainId, toToken: toToken, toAddress: signer.address, slippage: 1, }; console.log("Parameters:", params); // Get the swap route using Squid API const routeResult = await getRoute(params); const route = routeResult.data.route; const requestId = routeResult.requestId; const quoteId = route.quoteId; // Save quoteId — required for Squid Intents status tracking console.log("Calculated route:", route); console.log("requestId:", requestId); console.log("quoteId:", quoteId); const transactionRequest = route.transactionRequest; // Execute the swap transaction const tx = await signer.sendTransaction({ to: transactionRequest.target, data: transactionRequest.data, value: transactionRequest.value, gasPrice: await provider.getGasPrice(), gasLimit: transactionRequest.gasLimit, }); console.log("Transaction Hash:", tx.hash); const txReceipt = await tx.wait(); // Show the transaction receipt with Axelarscan link const axelarScanLink = "https://axelarscan.io/gmp/" + txReceipt.transactionHash; console.log(`Finished! Check Axelarscan for details: ${axelarScanLink}`); // Update transaction status until it completes await updateTransactionStatus(txReceipt.transactionHash, requestId, quoteId); })(); ``` # Swap & Bridge Example The swap and bridge example leverages the same index.js code included in the [API Overview section](/old-v2-documentation-deprecated/api). **The following actions take place in the index.js:** * Loading necessary packages and environmental variables * Defining route parameters, RPC provider, and wallet signer * Creating the route request and the transaction status functions * Defining the route parameters and requesting the route * Approve the Squid Contract to spend the tokens * Executing the route transactions * Checking the status of the transactions ```typescript import { ethers } from "ethers"; import axios from "axios"; 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.FROM_CHAIN_RPC_ENDPOINT!; // Define chain and token addresses const fromChainId = "56"; // BNB const toChainId = "42161"; // Arbitrum const fromToken = "0x55d398326f99059fF775485246999027B3197955"; // USDT const toToken = "0xaf88d065e77c8cC2239327C5EDb3A432268e5831"; // USDC // Define the amount to be sent const amount = "1000000000000000"; // Set up JSON RPC provider and signer const provider = new ethers.providers.JsonRpcProvider(FROM_CHAIN_RPC); const signer = new ethers.Wallet(privateKey, provider); // Function to get the optimal route for the swap using Squid API 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"]; // Retrieve request ID from response headers return { data: result.data, requestId: requestId }; } catch (error) { if (error.response) { console.error("API error:", error.response.data); } console.error("Error with parameters:", params); throw error; } }; // 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; } }; // 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"]; 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)); }; // 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; } }; // Set up parameters for swapping tokens (async () => { const params = { fromAddress: signer.address, fromChain: fromChainId, fromToken: fromToken, fromAmount: amount, toChain: toChainId, toToken: toToken, toAddress: signer.address, }; console.log("Parameters:", params); // Get the swap route using Squid API const routeResult = await getRoute(params); const route = routeResult.data.route; const requestId = routeResult.requestId; const quoteId = route.quoteId; // Save quoteId — required for Squid Intents status tracking console.log("Calculated route:", route); console.log("requestId:", requestId); console.log("quoteId:", quoteId); const transactionRequest = route.transactionRequest; // Approve the transactionRequest.target to spend fromAmount of fromToken await approveSpending(transactionRequest.target, fromToken, amount); // Execute the swap transaction const tx = await signer.sendTransaction({ to: transactionRequest.target, data: transactionRequest.data, value: transactionRequest.value, gasPrice: await provider.getGasPrice(), gasLimit: transactionRequest.gasLimit, }); console.log("Transaction Hash:", tx.hash); const txReceipt = await tx.wait(); // Show the transaction receipt with Axelarscan link const axelarScanLink = "https://axelarscan.io/gmp/" + txReceipt.transactionHash; console.log(`Finished! Check Axelarscan for details: ${axelarScanLink}`); // Update transaction status until it completes await updateTransactionStatus(txReceipt.transactionHash, requestId, quoteId); })(); ``` # Staking Example In this example, we utilize a [post-hook](/old-v2-documentation-deprecated/key-concepts/hooks/build-a-posthook) to swap from Binance to Arbitrum and lend on Arbit
프로젝트로 돌아가기