omAmount: 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;
console.log("Calculated route:", route);
console.log("requestId:", requestId);
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);
})();
```
# 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 Arbitrum.
This example can also be found in the [examples repo](https://github.com/0xsquid/examples/tree/main/V2/api/swapEVMToEVMAndLendPosthook).
```typescript
// Import necessary libraries
import { ethers } from "ethers";
import axios from "axios";
// Load environment variables from .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 swapped and deposited
const amount = "1000000000000000";
// 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,
]
);
// 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,
},
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) => {
const getStatusParams = {
transactionId: txHash,
requestId: requestId,
fromChainId: fromChainId,
toChainId: toChainId,
};
let status;
const completedStatuses = ["success", "partial_success", "needs_gas", "not_found"];
const maxRetries = 15; // 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, 20000)); // Wait for 10 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 () => {
// 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
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",
},
],
provider: "Squid", //This should be the name of your product or application that is triggering the hook
description: "Radiant Lend",
logoURI: "https://pbs.twimg.com/profile_images/1548647667135291394/W2WOtKUq_400x400.jpg", //This should be your product or applications logo
},
};
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;
console.log("Calculated route:", route);
console.log("requestId:", requestId);
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);
})();
```
# Cross-chain NFT Purchase Example
Robust documentation for a cross-chain NFT Purchase coming soon.
Please refer to this example of purchasing an [NFT on Polygon from any chain](https://github.com/0xsquid/examples/blob/main/V2/api/oldExamples/mintPolygonNftFromAnyChain/src/index.ts) from our [example repo.](https://github.com/0xsquid/examples/tree/main)
```typescript
// Import necessary libraries
import { ethers } from "ethers";
import axios from "axios";
// Load environment variables from the .env file
import * as dotenv from "dotenv";
dotenv.config();
const privateKey: string = process.env.PRIVATE_KEY!;
const integratorId: string = process.env.INTEGRATOR_ID!; // request via https://squidrouter.typeform.com/partnerships
const rpcEndpoint: string = process.env.RPC_ENDPOINT!;
const nftContractAddress: string = process.env.NFT_CONTRACT_ADDRESS!;
// Define chain and token addresses
const fromChainId = "1"; // Define departing chain, set to Ethereum by default
const polygonId = "137"; // Polygon
const nativeToken = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE"; // Define departing token
// Define amount to be sent
const amount = "10000000000000000";
// Import necessary ABI's
import nftContractAbi from "../abi/squidEasterEggNftAbi";
import erc20Abi from "../abi/erc20Abi";
// Set up JSON RPC provider and signer for source chain (Ethereum)
const provider = new ethers.providers.JsonRpcProvider(rpcEndpoint);
const signer = new ethers.Wallet(privateKey, provider);
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"];
return { data: result.data, requestId: requestId };
} catch (error) {
// Log the error response if it's available.
if (error.response) {
console.error("API error:", error.response.data);
}
console.error("Error with parameters:", params);
throw error;
}
};
const getStatus = async (params: any) => {
try {
const result = await axios.get("https://api.squidrouter.com/v1/status", {
params: {
transactionId: params.transactionId,
requestId: params.requestId,
fromChainId: params.fromChainId,
toChainId: params.toChainId,
},
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;
}
};
// Create contract interfaces and encode calldata
const nftContractInterface = new ethers.utils.Interface(nftContractAbi);
const mintEncodedData = nftContractInterface.encodeFunctionData("mint", [
signer.address,
]);
const erc20ContractInterface = new ethers.utils.Interface(erc20Abi);
const transferRemainingBalanceEncodeData =
erc20ContractInterface.encodeFunctionData("transfer", [signer.address, "0"]);
(async () => {
// Set up parameters for swapping tokens and minting NFT on Polygon
const params = {
fromAddress: signer.address,
fromChain: fromChainId,
fromToken: nativeToken,
fromAmount: amount,
toChain: polygonId,
toToken: nativeToken,
toAddress: signer.address,
slippage: 1, //optional, Squid will dynamically calculate if removed
quoteOnly: false,
// Customize contract call for minting NFT on Polygon
postHooks: [
{
callType: 0, // SquidCallType.DEFAULT
target: nftContractAddress,
value: "0",
callData: mintEncodedData,
payload: {
tokenAddress: nativeToken,
inputPos: 1,
},
estimatedGas: "50000",
},
{
callType: 1, // SquidCallType.FULL_TOKEN_BALANCE
target: nativeToken,
value: "0",
callData: transferRemainingBalanceEncodeData,
payload: {
tokenAddress: nativeToken,
inputPos: 1,
},
estimatedGas: "50000",
},
],
};
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;
console.log("Calculated route:", route);
console.log("requestId:", requestId);
const transactionRequest = route.transactionRequest;
// Execute the swap and minting transaction
const contract = new ethers.Contract(
transactionRequest.targetAddress,
nftContractAbi,
signer
);
const tx = await contract.send(transactionRequest.data, {
value: transactionRequest.value,
gasPrice: await provider.getGasPrice(),
gasLimit: transactionRequest.gasLimit,
});
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));
// Retrieve the transaction's route status
const getStatusParams = {
transactionId: txReceipt.transactionHash,
requestId: requestId,
fromChainId: fromChainId,
toChainId: polygonId,
};
const status = await getStatus(getStatusParams);
// Display the route status
console.log(`Route status: ${status.squidTransactionStatus}`);
})();
```
# SDK
## Overview
The SDK is ideal for integrating cross-chain swaps, bridges, and deposits into applications that utilize JavaScript or Typescript, while the API can be used for similar purposes in a more language-agnostic manner.
## 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'
```
## **Installing the SDK**
### From the terminal, install [our SDK](https://www.npmjs.com/package/@0xsquid/sdk)
```bash
npm install --save @0xsquid/sdk@2.8.20 # or higher
```
### Now in your typescript file
```typescript
import { Squid } from "@0xsquid/sdk"; // Import Squid SDK
// Initialize the Squid client with the base URL and integrator ID
const getSDK = (): Squid => {
const squid = new Squid({
baseUrl: "https://v2.api.squidrouter.com",
integratorId: integratorId,
});
return squid;
};
```
Next, explore the first [**Swap & Bridging with the Squid SDK** ](/old-v2-documentation-deprecated/api/swap-and-bridge-example)to understand the fundamentals.
# Cross-chain Swap Example
Here is an example of a cross-chain swap that you can run out of the box. Head to our [examples repo](https://github.com/0xsquid/examples/tree/main/V2/sdk/evmToEVMSwap), download the folder and run:
```
yarn install
```
Create a .env file and replace the values shared in the .env.example file. Then run
```
yarn start
```
This will run the index.ts below
```typescript
import { Squid } from "@0xsquid/sdk"; // Import Squid SDK
import { ethers } from "ethers"; // Import ethers library
import * as dotenv from "dotenv"; // Import dotenv for environment variables
dotenv.config(); // Load environment variables from .env file
// Retrieve environment variables
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!;
if (!privateKey || !integratorId || !FROM_CHAIN_RPC) {
console.error("Missing environment variables. Ensure PRIVATE_KEY, INTEGRATOR_ID, and FROM_CHAIN_RPC_ENDPOINT are set.");
process.exit(1);
}
// Define chain and token addresses
const fromChainId = "56"; // BNB chain ID
const toChainId = "42161"; // Arbitrum chain ID
const fromToken = "0x55d398326f99059fF775485246999027B3197955"; // USDT token address on BNB
const toToken = "0xaf88d065e77c8cC2239327C5EDb3A432268e5831"; // USDC token address on Arbitrum
// Define the amount to be sent (in smallest unit, e.g., wei for Ethereum)
const amount = "1000000000000000";
// Set up JSON RPC provider and signer using the private key and RPC URL
const provider = new ethers.providers.JsonRpcProvider(FROM_CHAIN_RPC);
const signer = new ethers.Wallet(privateKey, provider);
// Initialize the Squid client with the base URL and integrator ID
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");
// Set up parameters for swapping tokens
const params = {
fromAddress: signer.address,
fromChain: fromChainId,
fromToken: fromToken,
fromAmount: amount,
toChain: toChainId,
toToken: toToken,
toAddress: 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);
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 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)프로젝트로 돌아가기