Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I send ether to my smart contract's address?

contract_file = 'contract.sol'
contract_name = ':SimpleContract'

Solc = require('solc')
Web3 = require('web3')

web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
source_code = fs.readFileSync(contract_file).toString()

admin_account = web3.eth.accounts[0]

compiledContract = Solc.compile(source_code)
abi = compiledContract.contracts[contract_name].interface
bytecode = compiledContract.contracts[contract_name].bytecode;
ContractClass =  web3.eth.contract(JSON.parse(abi))

contract_init_data = {
    data: bytecode,
    from: admin_account,
    gas: 1000000,
}

deployed_contract = ContractClass.new(contract_init_data)
contract_instance = ContractClass.at(deployed_contract.address)

up until here, this works. However, one surprise was that the line msg.sender.transfer(amount); in my contract wouldn't compile on web3, despite getting that line straight from the common pattern section of the solidity docs. Had to use Solc instead, because transfer() wasn't in 0.4.6...

Isn't transfer() a core part of ethereum? I would have expected that to exist in v 0.1

Anyway, I then try to add ether to the contract like this:

load_up = {
    from: admin_account, 
    to: deployed_contract.address, 
    value: web3.toWei(1, 'ether'),
}
web3.eth.sendTransaction(load_up)

and I get:

Error: VM Exception while processing transaction: invalid opcode

which doesn't give me much to work with. What am I doing wrong, and how do I debug issues like this in the future?

like image 614
mavix Avatar asked Oct 23 '25 03:10

mavix


1 Answers

It turns out that I need to create a method on the contract with the payable keyword, for example:

function AddEth () payable {}

and then I can interact with my contract like this:

load_up = {
    from: admin_account, 
    to: deployed_contract.address, 
    value: web3.toWei(10, 'ether'),
}
deployed_contract.AddEth.sendTransaction(load_up)
like image 192
mavix Avatar answered Oct 26 '25 17:10

mavix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!