Execute ETH to USDT swap on Native
The following examples get transaction data to swap 1 ETH -> USDT on Ethereum and then submit the transaction data to Native Router to execute.
Typescript
import axios from 'axios';
import {ethers} from "ethers";
import routerAbi from './nativeRouter.json'
const apiKey = '' // Contact Native to get your API key;
const baseUrl = 'https://newapi.native.org/v1/';
const provider = 'https://eth.llamarpc.com';
const routerAddress = '0xEAd050515E10fDB3540ccD6f8236C46790508A76'; // Refer to Contract Address section -> NativeRouter (Proxy) for the address
const walletAddress = ''; // Your address
const privateKey = ''; // Your private key for the address above
// Swap input
const chain = 'ethereum'; // 1, 56
const tokenIn = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE'; // ETH
const tokenOut = '0xdAC17F958D2ee523a2206206994597C13D831ec7'; // USDT
const amount = 1; // in ether, not in wei
type FirmQuoteResult = {
orders: any[],
widgetFee: {
signer: string,
feeRecipient: string,
feeRate: number
},
widgetFeeSignature: string,
calldata: string,
amountIn: string,
amountOut: string,
fallbackData: string
}
async function callFirmQuote(): Promise<FirmQuoteResult> {
const endpoint = 'firm-quote?';
const headers: any = {
api_key: apiKey,
};
const response = await axios
.get(
`${baseUrl}${endpoint}chain=${chain}&token_in=${tokenIn}&token_out=${tokenOut}&amount=${amount}&address=${walletAddress}`,
{
headers,
}
)
console.log('Firm quote result', response.data)
return response.data;
}
function getRouterContract(): ethers.Contract {
const jsonRpcProvider = new ethers.JsonRpcProvider(provider);
const signer = new ethers.Wallet(privateKey, jsonRpcProvider);
const routerContract = new ethers.Contract(routerAddress, routerAbi, signer);
return routerContract
}
async function callRouterToSwap(firmQuoteResult: FirmQuoteResult) {
const routerContract = getRouterContract();
const args = {
orders: firmQuoteResult.calldata,
recipient: walletAddress,
amountIn: firmQuoteResult.amountIn,
amountOutMinimum: 0, // use this to specify your slippage tolerance
widgetFee: {
signer: firmQuoteResult.widgetFee.signer,
feeRecipient: firmQuoteResult.widgetFee.feeRecipient,
feeRate: firmQuoteResult.widgetFee.feeRate,
},
widgetFeeSignature: firmQuoteResult.widgetFeeSignature,
fallbackSwapDataArray: firmQuoteResult.fallbackData,
}
const functionName = firmQuoteResult.orders.length > 1 ? 'exactInput' : 'exactInputSingle'
const tx = await routerContract[functionName](args);
await tx.wait()
}
async function main() {
const firmQuoteResult = await callFirmQuote();
await callRouterToSwap(firmQuoteResult)
}
main();
Python
Last updated