开发者社区> 问答> 正文

用web3.js认证发送智能合约方法?

我对如何使怎么用Web3.js 1.0认证和发送提交智能合约的方法感到很困惑。 这是工作代码(通常我要先手动解锁帐户): var contract = new web3.eth.Contract(contractJson, contractAddress); contract.methods .transfer("0x0e0479bC23a96F6d701D003c5F004Bb0f28e773C", 1000) .send({ from: "0x2EBd0A4729129b45b23aAd4656b98026cf67650A" }) .on('confirmation', (confirmationNumber, receipt) => { io.emit('confirmation', confirmationNumber); }); 我得到这个错误(如果我不手动解锁的话): Returned error: authentication needed: password or unlock 上面的代码是Node.js中的一个API端点,我希望它以编程方式解锁或做身份认证(鉴权)。 在Web3.js 1.0中好像没有解锁帐户的方法。 我也不认为这是必要的(这就是我所困惑的)。因为我在管理帐号,所以我知道私钥是什么。 我想交易需要用私钥签名吗?这是正常的吗?这与unlocking the account账户解锁是否有关? 我又试着这样写代码: var contract = new web3.eth.Contract(contractJson, contractAddress);

var tx = { from: "...{fromAddress -- address that has the private key below}", to: "...", value: ... };

var signed = web3.eth.accounts.signTransaction(tx, "...{privateKey}");

console.log(signed);

var promise = web3.eth.sendSignedTransaction(signed); 我得到下面这个错误: Returned error: The method net_version does not exist/is not available 有什么最简单的方法来认证和发布提交一个以太坊交易? 理想情况下,我想用上面的第一种方法,因为它比较干净。

展开
收起
景凌凯 2020-03-18 18:42:04 936 0
1 条回答
写回答
取消 提交回答
  • 有点尴尬唉 你要寻找的东西已经被吃掉啦!

    用web3.js认证发送智能合约方法,此代码允许我使用我创建的帐户(web3.eth.accounts.create()),使用privateKey签署Node.js服务器端的交易,并将签名的交易发送到网络,而不必解锁用户帐户。 我用的是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);
    

    });

    2020-03-18 18:42:18
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
JavaScript函数 立即下载
Delivering Javascript to World 立即下载
编程语言如何演化-以JS的private为例 立即下载