简体   繁体   English

如何使用 web3 js 在 pancakeswap 上交换令牌

[英]how to swap tokens on pancakeswap using web3 js

I am trying to use pancakeswap contract method to simply swap BUSD to WBNB token, from metamask wallet.我正在尝试使用 pancakeswap 合约方法从 metamask 钱包简单地将 BUSD 交换为 WBNB 代币。 pancakeswap contract method is: pancakeswap 合约方法是:

var web3 = new Web3(new Web3.providers.HttpProvider('https://data-seed-prebsc-1-s1.binance.org:8545/'))

const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
   
    tokenToBuy = web3.utils.toChecksumAddress("0xae13d989daC2f0dEbFf460aC112a837C89BAa7cd") 
    spend = web3.utils.toChecksumAddress("0x78867BbEeF44f2326bF8DDd1941a4439382EF2A7")

    contract = new web3.eth.Contract(panabi, panRouterContractAddress, { from: sender_address });
  
    var swap = contract.methods.swapExactTokensForTokens(
        web3.utils.toWei("0.002", "ether"), 0, [spend, tokenToBuy], sender_address, web3.utils.toHex(Math.round(Date.now() / 1000) + 60 * 20)
    )
  
    var encodedABI = swap.encodeABI()
    nonc = await web3.eth.getTransactionCount(sender_address);

    ethereum
        .request({
            method: 'eth_sendTransaction',
            params: [
                {
                    from: sender_address,
                    to: panRouterContractAddress,
                    value: web3.utils.toHex(web3.utils.toWei("0.002", "ether")),
                    gasPrice: web3.utils.toHex(web3.utils.toWei("15", "gwei")),
                    gas: web3.utils.toHex(300000),
                    nonce: web3.utils.toHex(nonc),
                    data: encodedABI
                },
            ],
        })
        .then((txHash) => { console.log(txHash); })
        .then(() => console.log('Transaction sent!'))
        .catch((error) => console.error);

I am sure I am missing something.我确定我错过了一些东西。

Your spend = web3.utils.toChecksumAddress("0x78867BbEeF44f2326bF8DDd1941a4439382EF2A7") isn't a valid token address.您的spend = web3.utils.toChecksumAddress("0x78867BbEeF44f2326bF8DDd1941a4439382EF2A7")不是有效的令牌地址。

Likewise, your purchase token 0xae13d989daC2f0dEbFf460aC112a837C89BAa7cd isn't a valid token either.同样,您的购买令牌0xae13d989daC2f0dEbFf460aC112a837C89BAa7cd也不是有效令牌。

If you're trying to swap BUSD to WBNB, you need to change these variables to:如果您尝试将 BUSD 交换为 WBNB,则需要将这些变量更改为:

0xe9e7cea3dedca5984780bafc599bd69add087d56 (BUSD)

and

0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c (WBNB)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM