4

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

{
    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")
        });

我有这个错误:

错误:在给定选项和默认选项中都没有指定“发件人”地址。

from如果我在选项中写它怎么可能不是地址?

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

4

1 回答 1

3

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

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 秒,因此您应该稍等片刻。

于 2018-06-13T09:06:12.317 回答