Avatar
0
monkey Enlightened
monkey Enlightened
Blockchain: Call swapExactETHForTokens chuyển BNB to BUSD
Call swapExactETHForTokens chuyển BNB to BUSD từ javascript thế nào?
  • Answer
blockchain pancakeswap uniswap
Remain: 5
1 Answer
Avatar
monkey Enlightened
monkey Enlightened
  1. Lấy abi và địa chỉ contract ở đây: https://bscscan.com/address/0x10ed43c718714eb63d5aa57b78b54704e256024e#code
  2. Export từ metamask private key: metamask -> account details
  3. Code

const Web3 = require('web3');
const fs = require('fs');

let provider = new Web3.providers.HttpProvider("https://bsc-dataseed1.binance.org:443");
let web3 = new Web3(provider);

let account = {
    address: 'address',
    privateKey: 'private key'
};

let contractAddress = "0x10ED43C718714eb63d5aA57B78B54704E256024E"; // contract address not account address

let abi = [abi];


console.log('load contract');
let contract = new web3.eth.Contract(abi, contractAddress);
console.log('load contract done');

async function swapBNBToBUSD() {
    const nowInSeconds = Math.floor(Date.now() / 1000)
    const deadline = nowInSeconds + 900;
    const swapBNBToBUSDCall = contract.methods.swapExactETHForTokens(
        1,
        ['0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c', '0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56'],
        'address nhận busd',
        deadline
    );

    const swapBNBToBUSDTransaction = await web3.eth.accounts.signTransaction(
        {
            to: contractAddress,
            data: swapBNBToBUSDCall.encodeABI(),
            gas: 5500000,
            value: 10178  
        },
        account.privateKey
    );

    web3.eth.sendSignedTransaction(swapBNBToBUSDTransaction.rawTransaction).then(console.log);
};

swapBNBToBUSD();

Tham khảo thêm:

  1. https://docs.moonbeam.network/builders/build/eth-api/libraries/web3js/
  2. https://stackoverflow.com/questions/66037884/rinkeby-uniswap-swapexactethfortokens-fail-with-error-uniswapv2router-expire
  • 0
  • Reply