Web3.js – How to Send Ether to Contract Address Using Web3.js?

blockchaincrowdsalefallback-functiongo-ethereum

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.

Best Answer

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.

Related Topic