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

前端 未结 3 494
旧巷少年郎
旧巷少年郎 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:42

    Here's a complete example of how to sign a transaction without a local wallet account. Especially useful if you are using infura for the transaction. This was written for

    'use strict';
    const Web3 = require('web3');
    
    const wsAddress = 'wss://rinkeby.infura.io/ws';
    const contractJson = '(taken from solc or remix online compiler)';
    const privateKey = '0xOOOX';
    const contractAddress = '0xOOOX';
    const walletAddress = '0xOOOX';
    
    const webSocketProvider = new Web3.providers.WebsocketProvider(wsAddress);
    const web3 = new Web3(new Web3.providers.WebsocketProvider(webSocketProvider));
    const contract = new web3.eth.Contract(
      JSON.parse(contractJson),
      contractAddress
    );
    // change this to whatever contract method you are trying to call, E.G. SimpleStore("Hello World")
    const query = contract.methods.SimpleStore('Hello World');
    const encodedABI = query.encodeABI();
    const tx = {
      from: walletAddress,
      to: contractAddress,
      gas: 2000000,
      data: encodedABI,
    };
    
    const account = web3.eth.accounts.privateKeyToAccount(privateKey);
    console.log(account);
    web3.eth.getBalance(walletAddress).then(console.log);
    
    web3.eth.accounts.signTransaction(tx, privateKey).then(signed => {
      const tran = web3.eth
        .sendSignedTransaction(signed.rawTransaction)
        .on('confirmation', (confirmationNumber, receipt) => {
          console.log('=> confirmation: ' + confirmationNumber);
        })
        .on('transactionHash', hash => {
          console.log('=> hash');
          console.log(hash);
        })
        .on('receipt', receipt => {
          console.log('=> reciept');
          console.log(receipt);
        })
        .on('error', console.error);
    });
    

    Using

    "web3": "1.0.0-beta.30"

提交回复
热议问题