bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 27쪽 중 25쪽
);
// 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 mined
console.log("Swap transaction executed:", txReceipt.transactionHash);
})();
```
# 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";
// 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 radiantLendingPoolAddress: string = process.env.RADIANT_LENDING_POOL_ADDRESS!;
const usdcArbitrumAddress: string = process.env.USDC_ARBITRUM_ADDRESS!;
// 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";
// Import Radiant lending pool ABI
import radiantLendingPoolAbi from "../abi/radiantLendingPoolAbi";
// Import erc20 contract ABI
import erc20Abi from "../abi/erc20Abi";
import { ChainType } from "@0xsquid/squid-types";
import { Description } from "@ethersproject/properties";
// 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 () => {
// Set up JSON RPC provider and signer for source chain (Ethereum)
const provider = new ethers.providers.JsonRpcProvider(FROM_CHAIN_RPC);
const signer = new ethers.Wallet(privateKey, provider);
// Initialize Squid SDK
const squid = getSDK();
await squid.init();
console.log("Initialized Squid SDK");
// 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,
]
);
// 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, //optional, Squid will dynamically calculate if removed
quoteOnly: false,
postHooks: {
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",
},
],
description: "sample",
logoURI: "https://v2.app.squidrouter.com/images/icons/squid_logo.svg",
provider: signer.address,
},
};
console.log("Parameters:", params); // Printing the parameters for QA
// Get the swap route using Squid SDK
const { route, requestId } = await squid.getRoute(params);
console.log("Calculated route:", route.estimate.toAmount);
// Execute the swap transaction
const tx = (await squid.executeRoute({
signer,
route,
})) as unknown as ethers.providers.TransactionResponse;
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}`);
// 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: txReceipt.transactionHash,
requestId: requestId,
integratorId: integratorId,
fromChainId: fromChainId,
toChainId: toChainId,
};
const completedStatuses = ["success", "partial_success", "needs_gas", "not_found"];
const maxRetries = 10; // Maximum number of retries for status check
let retryCount = 0;
let status = await squid.getStatus(getStatusParams);
// Loop to check the transaction status until it is completed or max retries are reached
console.log(`Initial route status: ${status.squidTransactionStatus}`);
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 mined
console.log("Swap transaction executed:", txReceipt.transactionHash);
})();
```
# 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://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 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,
});
console.log("Status: ", status);
})();
```
# Key Concepts
## Overview
These concepts are functionalities that persist throughout Squid's Widget, API, and SDK that enable a seamless cross-chain experience for both users and developer. Please read through each feature to understand how they are implemented across Squid
## Squid Functionality
The functionality of the Squid boils down to **3 main functionalities**:
1. [**Route Requests**](/old-v2-documentation-deprecated/key-concepts/get-a-route)**(Fetching a Route):** Calculating the most optimized path from one asset to another.
2. [**Route Execution**](/old-v2-documentation-deprecated/key-concepts/execute-the-route)**:** The submission and execution of that path on chain.
3. [**Transaction Status**](/old-v2-documentation-deprecated/key-concepts/track-status)**:** The validation that the transaction has been completed.
There are **3 advanced functionalities** enhance Squid's API capabilities:
1. [**Transaction Hooks**](https://docs.squidrouter.com/) **(Pre/Post):** Allow transactions to be prepended(prehook) or appended(posthook) to asset transfers for a user. Think unstaking then transferring an asset or transfering an asset across chain then staking.
2. [**Boost:** ](/old-v2-documentation-deprecated/key-concepts/boost)Squids novel boost functionality allows cross-chain transactions to be settled in less than 20seconds by using an intent-model, a smart contract overlay which allows a provider to optimistically fulfill a transaction.
3. [**Collecting Fees**](/old-v2-documentation-deprecated/key-concepts/collect-fees-1)**:** Always integrators to collect fees associated with transactions. Note, this function is currently not available for v2 yet.
# Route Request Parameters
Building with Squid, fundamentally starts with requesting a route.
The `getRoute` type is used to define the parameters required for bridging assets between different blockchain networks.
```typescript
const params = {
fromChain: number | string; //the chainID assets are being bridged FROM
toChain: number | string; //the chainID assets are being bridged TO
fromToken: string; //the asset address being swapped FROM, "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" for native assets
toToken: string; // The asset address being swapped TO, "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" for native assets
fromAmount: string; // The unadjusted decimal amount assets
fromAddress: string; // The address FROM which assets are being sent to be bridged
toAddress: string; // The address TO which bridged assets will be sent to
slippage?: number; //OPTIONAL, If set it determines the max slippage across the route (0.01-99.99) 1 = 1% slippage.
quoteOnly?: boolean; //OPTIONAL, If true, returns only a quote for the route. Omits transaction data needed for execution. Defaults to false
enableExpress?: boolean; //OPTIONAL, Utilizes Axelar's Express message passing for an additional small fee to expedite the crosschain transaction. Defaults to true
prefer?: string[]; // When set, the route response will prefer routes from the DEX corresponding to the string. EVM chains only supported.
receiveGasOnDestination?: boolean;
collectFees?: {
integratorAddress: string; //The EVM address of the integrator that will receive the fee
fee: number; // The amount in "basis points" for the fee. 50 = 0.05%. there is currently soft limit of 1% fee allowed for each tx.
};
fallbackAddresses?:{
//For Cosmos routes where either the source or destination chains are not of coinType 118, the SDK necessitates an additional argument.
///This argument is fallbackAddresses, which is an array of objects containing an address and its associated coin type.
//See more here
coinType: number;
address: string;
};
};
```
## Parameter Summaries
* **fromChain** (`number | string`): The chain ID of the network from which assets are being bridged.
* **toChain** (`number | string`): The chain ID of the network to which assets are being bridged.
* **fromToken** (`string`): The address of the asset being swapped from. Use "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" for native assets.
* **toToken** (`string`): The address of the asset being swapped to. Use "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" for native assets.
* **fromAmount** (`string`): The unadjusted decimal amount of assets being transferred.
* **fromAddress** (`string`): The address from which assets are being sent for bridging.
* **toAddress** (`string`): The address to which bridged assets will be sent.
* **slippage** (`number`, optional): Maximum allowable slippage across the route (range: 0.01-99.99). A value of 1 represents 1% slippage.
* **quoteOnly** (`boolean`, optional): If true, only a quote for the route is returned without transaction data needed for execution. Defaults to false.
* **enableExpress** (`boolean`, optional): Utilizes Axelar's Express message passing for a small fee to expedite the cross-chain transaction. Defaults to true.
* **customContractCalls** (`ContractCall[] | CustomCosmosContractCall[]`, optional): Custom contract calls to be included in the route.
* **prefer** (`string[]`, optional): Prefers routes from the specified DEXs. Only supported on EVM chains.
* **receiveGasOnDestination** (`boolean`, optional): Determines whether to receive gas on the destination chain.
* **collectFees** (`{ integratorAddress: string; fee: number; }`, optional): Specifies the integrator's address to receive the fee and the fee amount in basis points (e.g., 50 = 0.05%). There is a soft limit of 1% fee per transaction.
* **fallbackAddresses** (`{ coinType: number; address: string; }[]`, optional): For Cosmos routes where the source or destination chains are not of coinType 118. Requires an array of objects containing an address and its associated coin type.
# Get a route
{% hint style="info" %}
We recommend getting a new route or quote every 20 seconds to refresh prices.
{% endhint %}
{% tabs %}
{% tab title="SDK" %}
```typescript
// Set up parameters for swapping tokens and depositing into Radiant lending pool
const params = {
fromAddress: signer.address,
fromChain: arbitrumId,
fromToken: usdcArbitrumAddress,
fromAmount: amount,
toChain: polygonId,
toToken: nativeToken,
toAddress: signer.address,
slippage: 1,
quoteOnly: false,
};
// Get the swap route using Squid SDK
const { route, requestId } = await squid!.getRoute(params);
```
You can then explore the route response. This includes all the information on your quote `route.estimate` and all the data needed to generate a transaction `route.transactionRequest`.
{% endtab %}
{% tab title="API" %}
```typescript
// 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;
}
};
// Get the swap route using Squid API
const routeResult = await getRoute(params);
const route = routeResult.data.route;
const requestId = routeResult.requestId;
console.log("Calculated route:", route);
console.log("requestId:", requestId);
```
{% endtab %}
{% tab title="Widgets" %}
All Squid widgets will get a route when the user can entered all the necessary parameters.
Widgets refresh quotes every 20 seconds.
{% endtab %}
{% endtabs %}
# Execute the route
{% tabs %}
{% tab title="SDK" %}
```typescript
// Execute the swap and deposit transaction
const tx = (await squid.executeRoute({
signer,
route,
})) as unknown as ethers.providers.TransactionResponse;
const txReceipt = await tx.wait();
```
If you want to exe프로젝트로 돌아가기