Search code examples
javascriptethereumsolidityweb3jsremix

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.

This is my solidity function which works fine in remix:

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

Here is what I have in my js file

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.

When I tap the green button and try to send the ether to the other account I get this error in my metamask enter image description here

Any ideas how I could get this to work?


Solution

  • The web3 API is sometimes confusing because there are significant changes between 0.20.x and 1.0. It's hard to tell which version you're using.

    If you're on 0.20.x, the call should be

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

    If you're using 1.0, the call would be

    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.