9

I want to send ether to this contract's contribute function using web3.js

I'm trying below code for the same but this doesn't work for me.

var AbiOfContract = 'abi_code';
var contractAddress = "0x8bbc*************************";
var contract1 = web3.eth.contract(JSON.parse(AbiOfContract)).at(contractAddress);

contract1.contribute({"to": contractAddress ,"from": accounts[1], "value": web3.toWei("10.0", "ether")},"password");
contract CrowdFunder {

    function contribute()
    public
    inState(State.Fundraising) payable returns (uint256)
    {
        contributions.push(
            Contribution({
                amount: msg.value,
                contributor: msg.sender
                })
            );
        totalRaised += msg.value;
        currentBalance = totalRaised;
        LogFundingReceived(msg.sender, msg.value, totalRaised);
        checkIfFundingCompleteOrExpired();
        return contributions.length - 1;
    }
}

Any help regarding this will be highly appreciated.

1
  • You should not have included "password" at the end of contribute call. To unlock your wallet you have to execute in geth personal.unlockAccount.
    – Ismael
    Commented Oct 23, 2017 at 20:05

3 Answers 3

11

If you want to accept the Ether in a smart contract then you should have a fallback function. The fallback function will be called by default when someone transfers ETH to the contract address.

contract Crowdfunder{
   function() Crowdfunder { }
   function() payable {
      contributions.push(
        Contribution({
            amount: msg.value,
            contributor: msg.sender
            })
        );
    totalRaised += msg.value;
    currentBalance = totalRaised;
    LogFundingReceived(msg.sender, msg.value, totalRaised);
    checkIfFundingCompleteOrExpired();
  }
}

In web3js you can send through the normal transaction.

let send = web3.eth.sendTransaction({from:eth.coinbase,to:contract_address, value:web3.toWei(0.05, "ether")});

For further reference regarding fallback function check here.

11
  • 1
    I have used fallback function but it is not working.
    – Rahul Sati
    Commented Oct 23, 2017 at 13:04
  • A fallback function is not required, any function with payable modifier should be able to accept ether.
    – Ismael
    Commented Oct 23, 2017 at 20:00
  • 1
    If I want to send ETH to a particular function with payable modifier then how I can call that function in web3.js sendTransaction function??
    – Rahul Sati
    Commented Oct 24, 2017 at 4:55
  • 1
    Mycontract.methods.Mymethod(params).send(from:"address", to:"contractaddress", value:"in wei"); it will do your needs Commented Oct 24, 2017 at 5:09
  • 1
    If anyone wants to send Ether to your contract address then you need to have fallback function with a payable modifier. In web3 you can achieve that by Mycontract.methods.send(from:"address", to:"contractaddr", to:"value"); When they send Ether to your contract addr by default fallback function will get triggered. Commented Oct 24, 2017 at 5:42
1

At the time of writing, funding a contract is best done with the receive function.

contract CrowdFunder {
  receive () external payable {
    // what to do when receiving funds...
  }
}

You can then trigger the receive function by sending ether directly to the contract address.

web3.eth.sendTransaction({
  from: senderAddress,
  to: contractAddress,
  value: web3.utils.toWei('1', 'ether'),
});

It was previously possible to do so with the fallback function, which now has a limit of 2300 gas to perform operations (the receive function does not have a gas limit).

0

I was trying to write a test suite in Truffle where I initially fund my smart contract in order to operate certain operations.

Inside my Test script, I had something like this:

it("Funds the Smart Contract With Test Ether", async () => {
  const addressContract = await TriviaContract.address
  await web3.eth.sendTransaction({
    from: accounts[9],
    to: String(addressContract),
    value: String(await web3.utils.toWei("1", "ether"))
  });
  const ContractBalance = await web3.utils.fromWei(await web3.eth.getBalance(TriviaContract.address))
  console.log(ContractBalance);
})

Whenever I will run my test script, I would get an error that looks like this:

enter image description here

My transaction was reverting because I did not enable my Smart Contract to receive Ethers. All I had to do was add a special receive() function inside my smart contract and everything worked after that:

receive () external payable {
    // Do whatever you want when receiving funds...
  }

I hope this helps anyone out there who was experiencing the same issue.

Cheers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.