从新创建的帐户使用 web3 调用合约方法

Call contract methods with web3 from newly created account

我需要在不使用 MetaMask 的情况下从以太坊中的合约调用方法。我使用 Infura API 并尝试从最近使用 web3.eth.create() 方法创建的帐户调用我的方法。此方法 returns 对象如下:

{
    address: "0xb8CE9ab6943e0eCED004cG5834Hfn7d",
    privateKey: "0x348ce564d427a3311b6536bbcff9390d69395b06ed6",
    signTransaction: function(tx){...},
    sign: function(data){...},
    encrypt: function(password){...}
} 

我也在使用 infura 提供商:

 const web3 = new Web3(new Web3.providers.HttpProvider(
    "https://rinkeby.infura.io/5555666777888"
  ))

所以,当我尝试这样写的时候:

contract.methods.contribute().send({
          from: '0xb8CE9ab6943e0eCED004cG5834Hfn7d', // here I paste recently created address
          value: web3.utils.toWei("0.5", "ether")
        });

我有这个错误:

Error: No "from" address specified in neither the given options, nor the default options.

如果我在from选项中写它怎么可能没有发件人地址??

P.S。使用 Metamask,我的应用程序运行良好。但是当我从 MetaMask 注销并尝试创建新帐户并使用它时,我遇到了这个问题。

事实上,我们不能只从新创建的地址发送交易。我们必须用我们的私钥签署这笔交易。例如,我们可以为 NodeJS 使用 ethereumjs-tx 模块。

const Web3 = require('web3')
const Tx = require('ethereumjs-tx')

let web3 = new Web3(
  new Web3.providers.HttpProvider(
    "https://ropsten.infura.io/---your api key-----"
  )
)

const account = '0x46fC1600b1869b3b4F9097185...'; //Your account address
const privateKey = Buffer.from('6e4702be2aa6b2c96ca22df40a004c2c944...', 'hex');
const contractAddress = '0x2b622616e3f338266a4becb32...'; // Deployed manually
const abi = [Your ABI from contract]
const contract = new web3.eth.Contract(abi, contractAddress, {
  from: account,
  gasLimit: 3000000,
});

const contractFunction = contract.methods.createCampaign(0.1); // Here you can call your contract functions

const functionAbi = contractFunction.encodeABI();

let estimatedGas;
let nonce;

console.log("Getting gas estimate");

contractFunction.estimateGas({from: account}).then((gasAmount) => {
  estimatedGas = gasAmount.toString(16);

  console.log("Estimated gas: " + estimatedGas);

  web3.eth.getTransactionCount(account).then(_nonce => {
    nonce = _nonce.toString(16);

    console.log("Nonce: " + nonce);
    const txParams = {
      gasPrice: 100000,
      gasLimit: 3000000,
      to: contractAddress,
      data: functionAbi,
      from: account,
      nonce: '0x' + nonce
    };

    const tx = new Tx(txParams);
    tx.sign(privateKey); // Transaction Signing here

    const serializedTx = tx.serialize();

    web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')).on('receipt', receipt => {
      console.log(receipt);
    })
  });
});

交易时间约为 20-30 秒,因此您应该稍等片刻。