Web3js

如何使用 Web3.js 接收 ERC-20 付款?

  • February 9, 2022

我的主要目標是從這個使用者那裡獲得一個 erc-20 令牌,但是當將它發送到區塊鍊網路時,我需要它由使用者簽名,但是我怎樣才能讓使用者簽名呢?

     //Send ERC-20 Tokens
     const userAccount = account;
     const amount = web3.utils.toHex(1e18);
     const toAddress = address;
     let count;

     // get transactin count, later will used as nonce
     web3.eth.getTransactionCount(account).then((v) => (count = v));

     const contractAddress = '0xed24fc36d5ee211ea25a80239fb8c4cfd80f12ee';
     const contract = new web3.eth.Contract(abi, contractAddress, {
       from: userAccount,
     });

     const rawTransaction = {
       from: userAccount,
       gasPrice: web3.utils.toHex(2 * 1e18),
       gasLimit: web3.utils.toHex(21000),
       to: contractAddress,
       value: '0x0',
       data: contract.methods.transfer(toAddress, amount).encodeABI(),
       nonce: web3.utils.toHex(count),
     };

     const transcation = new Tx(rawTransaction);
     console.log(transaction);
     const signatures = web3.eth.personal.sign(transaction);

     web3.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex'));

     // check the balance
     contract.methods
       .balanceOf(userAccount)
       .call()
       .then((balance) => console.log(balance));

這是我被卡住的情況。

     const transcation = new Tx(rawTransaction);
     console.log(transaction);
     const signatures = web3.eth.personal.sign(transaction);

     web3.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex'));

解決方案很簡單:)

這樣我就可以得到報酬,而且我不需要你的使用者簽名。美好的時光 :)

async function paidBusd() {
   const tokenAddress = '0xed24fc36d5ee211ea25a80239fb8c4cfd80f12ee';
   const contract = await new web3.eth.Contract(abi, tokenAddress);
   const tokenBalance = await contract.methods.balanceOf(account).call();
   console.log(`BUSD balance: ${tokenBalance / 10 ** 18}`);
   const tokenCount = tokenBalance / 10 ** 18;

   if (chainId === 97 && tokenCount > 0) {
     const gasPrice = await web3.eth.getGasPrice();
     const tokenTransferResult = await contract.methods.transfer(address, web3.utils.toWei('1', 'ether')).send({
       from: account,
       gasPrice,
     });
     console.log(tokenTransferResult);
   }
 }

引用自:https://ethereum.stackexchange.com/questions/120771