简体   繁体   English

使用Web3.js将价值从Solidity合同转移到Ganache帐户

[英]Transfer Value From Solidity Contract To Ganache Account With Web3.js

I'm trying to transfer the balance of my contract to a ganache account from the UI. 我正在尝试将UI的合同余额转移到ganache帐户。

This is my solidity function which works fine in remix: 这是我的solidity函数,可以在混音中正常工作:

function tapGreen(address _receiverAddress) onlySwiper payable public {
    _receiverAddress.transfer(this.balance); 
}

Here is what I have in my js file 这是我的js文件中的内容

swipeRight: function() {
    console.log(addressInput.value);
    App.contracts.HackathonDapp.deployed().then(function (instance) {
        return instance.tapGreen(addressInput.value).sendTransaction ({
            from: web3.eth.accounts[1],
            value: web3.eth.getBalance(contracts.address) 
});

The addressInput.value comes from an HTML form. addressInput.value来自HTML表单。

When I tap the green button and try to send the ether to the other account I get this error in my metamask 当我点击绿色按钮并尝试将以太币发送到另一个帐户时,我在Metamask中收到此错误 在此处输入图片说明

Any ideas how I could get this to work? 有什么想法可以使它起作用吗? Thanks. 谢谢。

The web3 API is sometimes confusing because there are significant changes between 0.20.x and 1.0. Web3 API有时令人困惑,因为在0.20.x和1.0之间有重大变化。 It's hard to tell which version you're using. 很难确定您使用的是哪个版本。

If you're on 0.20.x, the call should be 如果您使用的是0.20.x,则致电应为

instance.tapGreen.sendTransaction(addressInput.value, {
    from: fromAccount,
    value: valueInWei 
});

If you're using 1.0, the call would be 如果您使用的是1.0,则调用方式为

instance.methods.tapGreen(addressInput.value).send({
    from: fromAccount,
    value: valueInWei 
});

Note that I purposely changed the values in the transaction object to variables since the synchronous versions of web3.eth.account and web3.eth.getBalance are not available in 1.0 and it's best practice to use the async versions (using callbacks) in 0.20.x as well. 请注意,我有意将事务对象中的值更改为变量,因为web3.eth.accountweb3.eth.getBalance的同步版本在1.0中不可用,并且最佳实践是在0.20中使用异步版本(使用回调)。 x也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM