Web3js

如何使用 web3 使用密鑰簽署 erc20 合約呼叫

  • May 9, 2020

我正在呼叫 Kovan 測試網上的 Dai 合約,以促進作為輸入輸入的任意兩個地址之間的交易。我能夠成功地進行讀取呼叫,但我意識到我需要為每個寫入呼叫使用密鑰來簽署交易。我如何使用 web3 做到這一點?為了清楚起見,我在下面有我的程式碼:

const Web3 = require("web3");
const axios = require('axios');
const WebSocket = require('ws');
const Web3Utils = require('web3-utils');

  if (typeof web3 !== 'undefined') {
       web3 = new Web3(web3.currentProvider);
   } else {
       // set the provider you want from Web3.providers
       web3 = new Web3(new Web3.providers.WebsocketProvider("wss://kovan.infura.io/ws/v3/d28ff5674c0848ada11af62d25c6a2f1"));
   }
   web3.eth.defaultChain = 'kovan';
   var DaiContract = new web3.eth.Contract('ABI-HERE','0xC4375B7De8af5a38a93548eb8453a498222C4fF2');
$("#button").click(function() {
       DaiContract.methods.transferFrom($("#address1").val(), $("#address2").val(), $("#amount").val()).call()
       .then(function(result){
           $("#result").html("Successfully transferred " + $("amount").val() + " Dai.");
           DaiContract.methods.balanceOf($("#address1").val()).call()
           .then(function(result){
               console.log('Remaining balance in address1 : ' + value);
           })
           .catch(function(error){
               console.error('Error : ' + error);
           });
       })
       .catch(function(error){
           console.error('Error : ' + error);
           $("#result").html("Transfer failed");
       });
   });

給出以下錯誤:

在此處輸入圖像描述

使用 web3 v1.2.x,您可以使用:

async function send(web3, privateKey, gasPrice, transaction, value = 0) {
   const address = web3.eth.accounts.privateKeyToAccount(privateKey).address;
   const options = {
       to      : transaction._parent._address,
       data    : transaction.encodeABI(),
       gas     : await transaction.estimateGas({from: address, value: value}),
       gasPrice: gasPrice,
       value   : value
   };
   const signed  = await web3.eth.accounts.signTransaction(options, privateKey);
   const receipt = await web3.eth.sendSignedTransaction(signed.rawTransaction);
   return receipt;
}

然後,例如,您可以從async函式中呼叫它,如下所示:

const transaction = DaiContract.methods.transferFrom($("#address1").val(), $("#address2").val(), $("#amount").val());
const receipt = await send(web3, YourPrivateKey, YourGasPrice, transaction);
console.log(receipt);

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