solidity -> type

  • arrom
  • 更新于 2022-11-12 16:45
  • 阅读 1102

solidity -> type

type

  • type(x) ->返回x类型的对象信息
  • type(x).name ->合约的名字
  • type(x).creattionCode ->合约部署时的bytecode
  • type(x).runtimecode ->合约运行时的bytecode
/**
 * @title Storage
 * @dev Store & retrieve value in a variable
 */
contract Storage {
    string public str;
    constructor(string memory _str) {
        str = _str;
    }

    uint256 number;

    /**
     * @dev Store value in variable
     * @param num value to store
     */
    function store(uint256 num) public {
        number = num;
    }

    /**
     * @dev Return value 
     * @return value of 'number'
     */
    function retrieve() public view returns (uint256){
        return number;
    }

    function getInfo() public pure returns(string memory name) {
        name = type(Storage).name;
        // creationCode 和runtimeCode不能在这个合约自己内部使用,防止会出现循环调用问题
        // creationCode = type(Storage).creationCode;
        // runtimeCode = new type(Storage).runtimeCode;
    }
}

contract TestStorage {
    Storage s;
    constructor(Storage _address) {
        s = _address;
    }

    function getInfo() public view returns(bytes memory creationCode, bytes memory runtimeCode) {
        creationCode = type(Storage).creationCode;
        runtimeCode = type(Storage).runtimeCode;
    }
}
点赞 2
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
arrom
arrom
江湖只有他的大名,没有他的介绍。