How to authenticate and send contract method using web3.js 1.0

前端 未结 3 477
旧巷少年郎
旧巷少年郎 2020-12-29 15:35

I am confused about how I should be executing a contract\'s method using the web3 1.0 library.

This code works (so long as I manually unlock the account first):

3条回答
  •  囚心锁ツ
    2020-12-29 15:53

    This code allows me to sign a transaction server-side (node.js) using the privateKey from the account I created (using web3.eth.accounts.create()), and send the signed transaction to the network without having to unlock the account.

    I am using Geth 1.7.1

      var contract = new web3.eth.Contract(contractJson, contractAddress);
      var transfer = contract.methods.transfer("0x...", 490);
      var encodedABI = transfer.encodeABI();
    
      var tx = {
        from: "0x...",
        to: contractAddress,
        gas: 2000000,
        data: encodedABI
      }; 
    
      web3.eth.accounts.signTransaction(tx, privateKey).then(signed => {
        var tran = web3.eth.sendSignedTransaction(signed.rawTransaction);
    
        tran.on('confirmation', (confirmationNumber, receipt) => {
          console.log('confirmation: ' + confirmationNumber);
        });
    
        tran.on('transactionHash', hash => {
          console.log('hash');
          console.log(hash);
        });
    
        tran.on('receipt', receipt => {
          console.log('reciept');
          console.log(receipt);
        });
    
        tran.on('error', console.error);
      });
    

提交回复
热议问题