bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 27쪽 중 23쪽
fined
```
This error can be fixed by installing explicitly the @wagmi/connectors package
# Stake widget
Squid provides a react component or iframe widget for quickly building a "Stake or deposit from any chain" flow.
This uses Squid's [Broken mention](broken://pages/19kRhbLXejm0jXx6sIDa) feature, where the Squid contract can make arbitrary calls to any contract after a bridge 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***** channel**.
### Installation
{% hint style="info" %}
To install the widget you need to register a partner ID with the Squid Team. Squid issues Integrator IDs on a limited basis upon review; please [submit a partnership request](https://squidrouter.typeform.com/partnerships) to acquire one.
{% endhint %}
```tsx
<
SquidStakingWidget
config={{
integratorId: "<partner-id>",
// ... Other config options, such as theme, titles, etc.
}} />
```
`integratorId` for Squid to keep track of partners; submit a [partnership request](https://squidrouter.typeform.com/partnerships) to acquire it.
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: [Broken mention](broken://pages/19kRhbLXejm0jXx6sIDa)
### 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,
}}
/>
);
}
```
# Quick Start
The Quick Start section is intended to give you a preview of the implementations of Squid's SDK, API, and Widget.
Remember you must have an [**integrator-id**](https://squidrouter.typeform.com/partnerships) **to be able to implement one of these applications.** (Squid issues Integrator IDs on a limited basis and upon review via a partnership request.)
{% tabs %}
{% tab title="SDK" %}
Example of a cross-chain swap from Avalanche-AVAX to Polygon-MATIC.
First, install the Squid SDK and Squid types:
<pre class="language-typescript"><code class="lang-typescript"><strong>npm i @0xsquid/sdk@2.8.0-beta.0 @0xsquid/squid-types # 2.8.0-beta.0
</strong></code></pre>
```typescript
import { Squid } from "@0xsquid/sdk"
import { ethers } from "ethers"
const userAddress = "<your address>"
const integratorId = "<your integrator id>"
const squid = new Squid({
baseUrl: "https://v2.api.squidrouter.com",
integratorId: integratorId
})
// initialize the Squid client
await squid.init()
const { route } = await squid.getRoute({
fromChain: "43114", // Avalanche
fromAmount: "10000000000000000", // 0.1 AVAX
fromToken: "0xEEeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
toChain: "137", // Polygon
toToken: "0xEEeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
fromAddress: userAddress,
toAddress: userAddress,
})
const privateKey = "<your private key>"
const rpcUrl = "https://avalanche.drpc.org" // fromChain RPC URL
const provider = new ethers.JsonRpcProvider(rpcUrl)
const signer = new ethers.Wallet(privateKey, provider)
const result = await squid.executeRoute({
route,
signer })
console.log(result)
```
{% endtab %}
{% tab title="API" %}
Example for getting a route from Avalanche-AVAX to Polygon-MATIC:
```typescript
const integratorId = "<your-integrator-id>"
const userAddress = "<your-address>"
const result = await fetch("https://v2.api.squidrouter.com/v2/route",
method: "POST",
body: JSON.stringify({
fromChain: 43114, // Avalanche
toChain: 137, // Polygon
fromToken: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
toToken: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
fromAmount: "100000000000000000", // 0.1 AVAX
fromAddress: userAddress,
toAddress: userAddress,
}),
headers: {
"x-integrator-id": integratorId,
"Content-Type": "application/json"
}
})
const route = await result.json()
console.log(route)
```
{% endtab %}
{% tab title="Widget" %}
Install the Squid Widget React component:
```
npm i @0xsquid/widget
```
And import it in your app:
```typescript
import { SquidWidget } from "@0xsquid/widget"
export default function App() {
const config = {
companyName: "Squid Widget",
integratorId: "<your integrator id>",
slippage: 1,
instantExec: true,
infiniteApproval: false,
apiUrl: "https://api.squidrouter.com",
} as AppConfig;
return <SquidWidget config={config} />
}
```
{% endtab %}
{% endtabs %}
# 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.
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,
},
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 = 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;
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);
})();
```
# 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,
},
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 = 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, fr프로젝트로 돌아가기