php 调用eth智能合约,以太坊常见问题和错误

我对如何使怎么用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

有什么最简单的方法来认证和发布提交一个以太坊交易?

理想情况下,我想用上面的第一种方法,因为它比较干净。

解决方法

用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);

});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值