3
votes
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?

1
Can you post the code of your contract? Which version of solc are you using? And what kind of node do you use (main,test or local testrpc?) - Gerben

1 Answers

5
votes

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)