This example uses Binance Chain network; however, it can be replicated on any network supported by VulpeFI Aggregation Protocol
Checking allowances
Step 1: Set Up Your Environment
First, import the necessary Node.js libraries and set up your environment variables.
constWeb3=require('web3'); // Import the Web3 library for interacting with Ethereumconstfetch=require('node-fetch'); // Import the fetch library for making HTTP requestsconstchainId=56; // The chain ID for the Binance Smart Chain (BSC)constweb3RpcUrl='https://bsc-dataseed.binance.org'; // The URL for the BSC node you want to connect toconstwalletAddress='0x...xxx'; // Set your wallet address (replace '0x...xxx' with your actual wallet address)const privateKey = '0x...xxx'; // Set the private key of your wallet (replace '0x...xxx' with your actual private key). NEVER SHARE THIS WITH ANYONE!
Step 2: Define Your Swap Parameters
Next, define the parameters for the swap you want to perform.
constswapParams= { fromTokenAddress:'0x...xxx',// The address of the token you want to swap from (VULPFI) toTokenAddress:'0x...xxx',// The address of the token you want to swap to (DAI) amount:'200000000000000000',// The amount of the fromToken you want to swap (in wei) fromAddress:'YOUR_WALLET_ADDRESS',// Your wallet address from which the swap will be initiated slippage:1,// The maximum acceptable slippage percentage for the swap (e.g., 1 for 1%) disableEstimate:false,// Whether to disable estimation of swap details (set to true to disable) allowPartialFill:false,// Whether to allow partial filling of the swap order (set to true to allow)};
INFO
For complete swap parameter descriptions, see this page.
amount: '200000000000000000': This value is used because VulpeFI token has 18 decimals as part of the ERC-20 token standard.
Step 3: Define API URLs and Initialize Web3 Libraries
Now, define the API URLs and initialize Web3. Web3 is a collection of libraries which allow you to interact with a local or remote Ethereum node, using HTTP, IPC, or WebSocket.
At this point, you'll have set up your environment, defined your swap parameters, defined your API endpoints, and checked the allowance for the token you are selling.
NOTE
If you haven't previously approved or swapped this asset using VulpFI Aggregation Protocol, then > Allowance: 0 will be displayed in the console. This means that the VulpFI router does not have access to swap this token within your wallet.
Creating the token allowance (approval) transaction
In order for the VulpFI aggregation protocol to access tokens in your wallet, you must create an approval transaction. This specifies that the VulpFI router is allowed to swap a specific amount of the token chosen.
CAUTION
Approval transactions require payment of a blockchain gas fee! This amount is deducted in the form of native tokens from your wallet.
Similar to the Allowance Check, you'll first need to set up your environment, define swap parameters and API endpoints, and initialize Web3 libraries.
constWeb3=require('web3');constfetch=require('node-fetch');constchainId=56;constweb3RpcUrl='https://bsc-dataseed.binance.org';constwalletAddress='0x...xxx'; // Set your wallet addressconstprivateKey='0x...xxx'; // Set private key of your wallet. Be careful! NEVER share this key with anyone!constswapParams= { fromTokenAddress:'0x...xxx',// VULPFI EXAMPLE toTokenAddress:'0x...xxx',// DAI EXAMPLE amount:'200000000000000000',//18 decimals (in gwei) fromAddress: walletAddress, slippage:1, disableEstimate:false, allowPartialFill:false,};// API endpointsconstbroadcastApiUrl='https://gateway.vulpfi.io/v1.1/'+ chainId +'/broadcast';constapiBaseUrl='https://api.vulpfi.com/v1/'+ chainId;constweb3=newWeb3(web3RpcUrl);
Implement helper functions to interact with the VulpFI API, including constructing the API request URL, broadcasting raw transactions, signing and sending transactions, and preparing approval transactions considering the gas limit.
// Construct full API request URLfunctionapiRequestUrl(methodName, queryParams) {return apiBaseUrl + methodName +'?'+ (newURLSearchParams(queryParams)).toString();}// Post raw transaction to the API and return transaction hashasyncfunctionbroadCastRawTransaction(rawTransaction) {returnfetch(broadcastApiUrl, { method:'post', body:JSON.stringify({ rawTransaction }), headers: { 'Content-Type':'application/json' } }).then(res =>res.json()).then(res => {returnres.transactionHash; });}// Sign and post a transaction, return its hashasyncfunctionsignAndSendTransaction(transaction) {const { rawTransaction } =awaitweb3.eth.accounts.signTransaction(transaction, privateKey);returnawaitbroadCastRawTransaction(rawTransaction);}// Prepare approval transaction, considering gas limitasyncfunctionbuildTxForApproveTradeWithRouter(tokenAddress, amount) {consturl=apiRequestUrl('/approve/transaction', amount ? { tokenAddress, amount } : { tokenAddress } );consttransaction=awaitfetch(url).then(res =>res.json());constgasLimit=awaitweb3.eth.estimateGas({...transaction, from: walletAddress });return {...transaction, gas: gasLimit };}
Prepare the transaction data for approval using the buildTxForApproveTradeWithRouter function and store it in transactionForSign.
consttransactionForSign=awaitbuildTxForApproveTradeWithRouter(swapParams.fromTokenAddress);console.log('Transaction for approve: ', transactionForSign);
Prompt the user to confirm the transaction using the yesno library. If confirmed, sign and send the transaction. Otherwise, exit without signing.
constok=awaityesno({ question:'Do you want to send a transaction to approve trade with VulpFI router?'});if (!ok) {returnfalse;}constapproveTxHash=awaitsignAndSendTransaction(transactionForSign);console.log('Approve tx hash: ', approveTxHash);
After running this code in the console, you should see something like this:
With the transaction hash, you can monitor its execution using the blockchain explorer.
For the Binance Chain, you can use bscscan.com:
BROKEN LINK
Making the Swap
CAUTION
Before proceeding, please confirm that your approval transaction has a status of Success!
Step 1: Set Up Environment and Define Swap Parameters
// Set up environment and import necessary librariesconstWeb3=require('web3');constfetch=require('node-fetch');// Define the chain ID and Web3 RPC URLconstchainId=56;constweb3RpcUrl='https://bsc-dataseed.binance.org';// Set your wallet address and private keyconstwalletAddress='0x...xxx';constprivateKey='0x...xxx';// Define the swap parametersconstswapParams= { fromTokenAddress:'0x...xxx',// VULPEFI EXAMPLE toTokenAddress:'0x...xxx',// DAI EXAMPLE amount:'200000000000000000', fromAddress: walletAddress, slippage:1, disableEstimate:false, allowPartialFill:false,};
// Define the API endpoints for broadcasting and interacting with VulpFeIconstbroadcastApiUrl='https://gateway.vulpefi.com/v1.1/'+ chainId +'/broadcast';constapiBaseUrl='https://api.vulpefi.com/v1/'+ chainId;// Create a new instance of Web3 using the provided RPC URLconstweb3=newWeb3(web3RpcUrl);// Construct the full API request URL based on the method and query parametersfunctionapiRequestUrl(methodName, queryParams) {return apiBaseUrl + methodName +'?'+ (newURLSearchParams(queryParams)).toString();}// Post a raw transaction to the VulpeFI API and return the transaction hashasyncfunctionbroadCastRawTransaction(rawTransaction) {returnfetch(broadcastApiUrl, { method:'post', body:JSON.stringify({ rawTransaction }), headers: { 'Content-Type':'application/json' } }).then(res =>res.json()).then(res => {returnres.transactionHash; });}// Sign and send a transaction using the provided private keyasyncfunctionsignAndSendTransaction(transaction) {const { rawTransaction } =awaitweb3.eth.accounts.signTransaction(transaction, privateKey);returnawaitbroadCastRawTransaction(rawTransaction);}
// Prepare the transaction data for the swap by making an API requestasyncfunctionbuildTxForSwap(swapParams) {consturl=apiRequestUrl('/swap', swapParams);// Fetch the swap transaction details from the APIreturnfetch(url).then(res =>res.json()).then(res =>res.tx);}// First, let's build the body of the transactionconstswapTransaction=awaitbuildTxForSwap(swapParams);console.log('Transaction for swap: ', swapTransaction);
// Prompt the user to confirm the transaction before signing and sending itconstok=awaityesno({ question:'Do you want to send a transaction to exchange with VulpeFI router?'});// Confirm that all parameters are specified correctly before signing the transactionif (!ok) {returnfalse;}// Sign and send the swap transaction, and retrieve the transaction hashconstswapTxHash=awaitsignAndSendTransaction(swapTransaction);console.log('Transaction Signed and Sent: ', swapTxHash);
After running this code in the console, you should see something like this: