ethereum - 为什么我无法将以太币发送到我的智能合约地址?

标签 ethereum solidity

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)

到目前为止,这都是有效的。然而,令人惊讶的是,这条线 msg.sender.transfer(金额); 在我的契约(Contract)中,尽管直接从 common pattern section 获取该行,但无法在 web3 上编译。 Solidity 文档的一部分。必须使用 Solc,因为 0.4.6 中没有 Transfer()...

transfer()不是以太坊的核心部分吗?我预计它会存在于 v 0.1

无论如何,我然后尝试将以太添加到合约中,如下所示:

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

我得到:

Error: VM Exception while processing transaction: invalid opcode

这并没有给我太多的帮助。我做错了什么,以后如何调试类似的问题?

最佳答案

事实证明,我需要使用 payable 关键字在合约上创建一个方法,例如:

函数AddEth()应付{}

然后我可以像这样与我的合约进行交互:

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

关于ethereum - 为什么我无法将以太币发送到我的智能合约地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44058803/

相关文章:

ethereum - 如何检查从地址到智能合约的eth转移

javascript - 以太坊 web3js 如何导入 "crypto-js"?

ethereum - 过滤掉 web3.js 中的空地址

javascript - 在发送交易之前如何估计当前的gas limit?

solidity - Metamask 未连接到本地主机 8545

typescript - 如何在zkSync中等待tx确认?

javascript - 契约(Contract)名称抛出未定义的错误?

solidity - 在 Remix - Solidity IDE 中,如何传递参数?

私有(private)以太坊 maxpeer

ethereum - 为什么这个 Solidity 函数在断言后返回 0?