Home | 简体中文 | 繁体中文 | 杂文 | 知乎专栏 | Github | OSChina 博客 | 云社区 | 云栖社区 | Facebook | Linkedin | 视频教程 | 打赏(Donations) | About
知乎专栏多维度架构微信号 netkiller-ebook | QQ群:128659835 请注明“读者”

14.13. 合约中实例化另一个合约

当合约已经部署到链上,如需扩展合约的功能可以采用此种方法。

		
pragma solidity ^0.4.24;

contract ERC20 {
    uint256 public totalSupply;
    uint public decimals;
    function balanceOf(address _address) constant public returns (uint256);
    function transfer(address _to, uint256 _value) public returns (bool success);
}
contract NetkillerBatchTransfer {

    ERC20 public token;
    
    constructor(address _contractAddress) public {
        token = ERC20(_contractAddress);
    }
    function getBalance(address _address) view public returns (uint256){
        return token.balanceOf(_address);
    }
}		
		
		

14.13.1. msg.sender 与 this 的区别

当一个合约访问另一个合约是,msg.sender 与 this 的区别是什么呢?

			
pragma solidity ^0.4.24;

/******************************************/
/*       Netkiller Mini TOKEN             */
/******************************************/
/* Author netkiller <netkiller@msn.com>   */
/* Home http://www.netkiller.cn           */
/* Version 2018-05-31 Fixed transfer bool */
/******************************************/

contract NetkillerMiniToken {

    constructor() public { }

    function test1() public view returns (address addr){
        return msg.sender;
    }
    function test2() public view returns (address addr){
        return this;
    }
}			
			
			

例子

			
Contract A: 0xf328c11c4df88d18fcbd30ad38d8b4714f4b33bf
Contract B: 0xb9b7e0cb2edf5ea031c8b297a5a1fa20379b6a0a
			
			

Contract A 调用 Contract B

			
msg.sender 	= 0xF328c11c4dF88d18FcBd30ad38d8B4714F4b33bF
this		= 0xB9B7e0cb2EDF5Ea031C8B297A5A1Fa20379b6A0a			
			
			

14.13.2. 地址格式

在合约中出现地址,例如下面:

			
pragma solidity ^0.4.24;
contract ERC20 {
    function totalSupply() public constant returns (uint);
    function balanceOf(address tokenOwner) public constant returns (uint balance);
    function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
    function transfer(address to, uint tokens) public returns (bool success);
    function approve(address spender, uint tokens) public returns (bool success);
    function transferFrom(address from, address to, uint tokens) public returns (bool success);

    event Transfer(address indexed from, address indexed to, uint tokens);
    event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}

contract TestContract{
    ERC20 public token = ERC20(0xAeeD5A0C200efA0670330d0C7509C854c52AF859);

    function tot() public view returns (uint){
        return token.totalSupply();
    }

    function balance(address _address) public view returns (uint){
        return token.balanceOf(_address);
    }

}			
			
			

合约中不支持全小写的地址。

			
正确的:0xAeeD5A0C200efA0670330d0C7509C854c52AF859
错误的:0xaeed5a0c200efa0670330d0c7509c854c52af859