三十五、智能合约收发 ETH 详解
一、合约接收 ETH
使用合约接收 ETH,需要在智能合约中定义这个函数 function () payable public {},之后就可以接收ETH了。并在最终需要时调用selfdestruct(owner);
杀死合约,取出合约中的所有 ETH 到 owner。
pragma solidity ^0.4.24;
contract NetkillerCashier {
function () payable public {}
function claim() public {
selfdestruct(owner);
}
}
二、自动退款合约
合约只收取 1 ETH 多余 ETH 将退给用户。
pragma solidity ^0.4.24;
contract Refund {
address owner = 0x0;
uint256 ticket = 1 ether;
constructor() public payable {
owner = msg.sender;
}
function () public payable {
require(msg.value >= ticket);
if (msg.value > ticket) {
uint refundFee = msg.value - ticket;
msg.sender.transfer(refundFee);
}
}
}
三、收款自动转账合约
合约收到 ETH 后自动转到 owner 账号中,所消耗的 gas 全部由发起转账的账号支付。
pragma solidity ^0.4.24;
contract NetkillerCashier {
address public owner;
constructor() public payable {
owner = msg.sender;
}
function () payable public {
owner.transfer(msg.value);
}
}
四、指定账号提取 ETH
pragma solidity ^0.4.24;
contract NetkillerCashier {
address public owner;
uint public amount;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
constructor() public {
owner = msg.sender;
}
function () public payable {
amount += msg.value;
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
function withdraw() onlyOwner public {
msg.sender.transfer(amount);
amount = 0;
}
}
function transferOwnership(address newOwner) // 可以修改合约所有人
function withdraw() // 提取 ETH 到 owner