以太坊合约部署及调用

作者: 古则 | 来源:发表于2018-04-11 17:58 被阅读14次

    部署合约

    合约代码

    contract XMT {
    
      mapping (address => uint) public balanceOf;
    
      function XMT() public {
        balanceOf[msg.sender] = 1000;
      }
    
      function transfer(address to, uint value) public {
        require(balanceOf[msg.sender] >= value);
        require(balanceOf[to] + value >= balanceOf[to]);
        balanceOf[msg.sender] -= value;
        balanceOf[to] += value;
      }
    }
    

    代码看懂了,下一步呢?怎么运行这代码?这代码到底在哪里运行呢?接着我们看部署过程。

    部署代码,你需要在以太坊的客户端里,把这段代码粘贴进去,并且按“部署”按钮。客户端就会把这种人可以读懂的代码编译成字节码,然后生成一笔从你的地址,发给一个空地址(0x0)的交易,并把字节码存在一个给定的字段里面(叫input),签名后发到整个网络上。接下来的操作和普通交易完全一样。矿工收到了以后立刻开始打包,算nonce,找到了以后再发送给全网络。这个可以被执行的代码,就永久的以只可读取不可更改的方式,存在了区块链上。

    通过eth_sendTransaction rpc部署,to为空,data为智能合约字节码,该rpc返回一个transaction hash(32bytes)
    通过eth_getTransactionReceipt transaction hash得到一个智能合约地址(类似账户地址20bytes)
    智能合约建立后会返回一个地址。每个币都唯一的对应于一个智能合约,也就是对应于一个地址。比如著名的EOS币,就是地址为0x86fa049857e0209aa7d9e616f7eb3b3b78ecfdb0的智能合约发行的。你可以把这个地址想象成以太坊世界里的门牌号。币是以这个唯一的门牌号来区分的,而不是那三位的名字。

    调用合约

    如:
    https://blog.csdn.net/ddffr/article/details/76549320
    (充值issue (address account, uint amount) 一节)

    通过eth_sendTransaction 或eth_call rpc调用智能合约,to为智能合约地址,data为调用代码编译后的字节码,该rpc返回一个transaction hash(32bytes)

    现在,合约的代码安全的存在区块链上了。那么接下来这些代码什么时候执行呢?

    一个智能合约里面有多个函数。调用智能合约里的一个函数,和发起一笔普通转账交易一样。很多的客户端已经内置进去了。你提供合约的地址,提供调用的函数,以及传入参数,然后发送消息就开始执行了。你可以把它理解为从门牌号的屋子里面拿东西或者放东西进到给定的屋子。

    消息发出以后,所有的矿工都执行这段代码,并且试图把结果打包到自己的数据块中,胜出的矿工获得挖矿的收益。所有的节点收到这个新的区块,也用自己的虚拟机执行一遍代码,确认结果和收到的块内结果无异之后才当作合法区块接受。

    区块链就是通过这种超额的浪费,看似无意义的算nonce,看似无意义的反反复复,没完没了的执行同一段代码,来保证了一个安全的系统。这事儿就跟早上叠被子晚上还得展开一样,看似不产生价值,实则是房(shu)间(ju)整(an)洁(quan)不可或缺的一环。

    判断调用是否成功

    通过eth_getTransactionReceipt
    返回
    Object - A transaction receipt object, or null when no receipt was found:

    • transactionHash: DATA, 32 Bytes - hash of the transaction.
    • transactionIndex: QUANTITY - integer of the transactions index position in the block.
    • blockHash: DATA, 32 Bytes - hash of the block where this transaction was in.
    • blockNumber: QUANTITY - block number where this transaction was in.
    • cumulativeGasUsed: QUANTITY - The total amount of gas used when this transaction was executed in the block.
    • gasUsed: QUANTITY - The amount of gas used by this specific transaction alone.
    • contractAddress: DATA, 20 Bytes - The contract address created, if the transaction was a contract creation, otherwise null.
    • logs: Array - Array of log objects, which this transaction generated.
    • logsBloom: DATA, 256 Bytes - Bloom filter for light clients to quickly retrieve related logs.

    It also returns either :

    • root : DATA 32 bytes of post-transaction stateroot (pre Byzantium)
    • status: QUANTITY either 1 (success) or 0 (failure)

    其中status为1时执行成功

    相关文章

      网友评论

        本文标题:以太坊合约部署及调用

        本文链接:https://www.haomeiwen.com/subject/fsyzhftx.html