Home | 簡體中文 | 繁體中文 | 雜文 | 知乎專欄 | Github | OSChina 博客 | 雲社區 | 雲棲社區 | Facebook | Linkedin | 視頻教程 | 打賞(Donations) | About
知乎專欄多維度架構 | 微信號 netkiller-ebook | QQ群:128659835 請註明“讀者”

14.11. 合約接收 ETH

首先你需要在智能合約中定義這個函數 function () payable public {},這時這個合約地址就可以接收ETH了。

測試方法,向合約地址發送ETH即可。

14.11.1. 調用 selfdestruct(msg.sender); 取出合約中的 ETH

			
			
			
			
			
			
pragma solidity ^0.4.24;

contract NetkillerCashier {

    function () payable public {}

    function claim() public {
        selfdestruct(msg.sender);
    }
}
			
			

https://ropsten.etherscan.io/tx/0x6504df0e18416c3c319f1f11f84ffa40a752b47c257faee58a7ef2c8ef78cc45

			
 Contract 0x0896827f5e3d2683763321bdf780bde1824f6137  
 TRANSFER  0.03 Ether from 0x0896827f5e3d2683763321bdf780bde1824f6137 to  0x22c57f0537414fd95b9f0f08f1e51d8b96f14029
 SELF-DESTRUCT Contract 0x0896827f5e3d2683763321bdf780bde1824f6137			
			
			

查看 Code https://ropsten.etherscan.io/address/0x0896827f5e3d2683763321bdf780bde1824f6137#code 顯示

			
Contract SelfDestruct called at TxHash 0x6504df0e18416c3c319f1f11f84ffa40a752b47c257faee58a7ef2c8ef78cc45			
			
			

14.11.2. 自動退款合約

本合約只收取 1 ETH 多餘 ETH 將退給用戶

			
pragma solidity ^0.4.24;

// Author: netkiller@msn.com
// Website: http://www.netkiller.cn

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);
        }
    }
}
			
			

14.11.3. 收款合約自動轉賬

合約收到ETH後自動轉到 owner 賬號中。

			
pragma solidity ^0.4.24;

contract NetkillerCashier {
    
    address public owner;

    constructor() public payable {
        owner = msg.sender;
    }
    function () payable public {
        owner.transfer(msg.value);
    }

}			
			
			

14.11.4. 指定賬號提取 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) 可以修改指定賬號提取 ETH
function withdraw()	提取 ETH 的函數
			
			

https://ropsten.etherscan.io/tx/0xadad8c4cd7649d825fb8c362e97f80c4821b07c97d423050289986bd75703b78

			
 Contract 0xb31fb5297340a06e1af3e21c1780b7001db6890a  
 TRANSFER  0.05 Ether from 0xb31fb5297340a06e1af3e21c1780b7001db6890a to  0x22c57f0537414fd95b9f0f08f1e51d8b96f14029