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

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

    A way to be able to call your contract methods without having to sign the transaction explicitly is this (web3js 1.0.0):

    const privateKey = 'e0f3440344e4814d0dea8a65c1b9c488bab4295571c72fb879f5c29c8c861937';
    const account = web3.eth.accounts.privateKeyToAccount('0x' + privateKey);
    web3.eth.accounts.wallet.add(account);
    web3.eth.defaultAccount = account.address;
    
    // ...
    contract = new web3.eth.Contract(JSON_INTERFACE, address);
    contract.methods.myMethod(myParam1, myParam2)
            .send({
                from: this.web3.eth.defaultAccount,
                gas: myConfig.gas,
                gasPrice: myConfig.gasPrice
            })
    

提交回复
热议问题