Truffle教程

Truffle 合约抽象

合约抽象对象在Javascript中表示一个合约,可以使用合约抽象对象与以太坊网络中的合约进行交互。
truff-contract包提供对合约抽象的支持。
注意
在前面章节中,我们提到过获取合约抽象对象的方法之一是,使用artifacts.require()函数获取。
示例
使用truffle示例中的MetaCoin合约。可以通过在truffle控制台中,执行 truffle unbox metacoin获取。
pragma solidity >=0.4.25 <0.6.0;
import "./ConvertLib.sol";
// this is just a simple example of a coin-like contract.
// It is not standards compatible and cannot be expected to talk to other
// coin/token contracts. if you want to create a standards-compliant
// token, see: https://github.com/ConsenSys/Tokens. Cheers!
contract MetaCoin {
    mapping (address => uint) balances;
    event Transfer(address indexed _from, address indexed _to, uint256 _value);
    constructor() public {
        balances[tx.origin] = 10000;
    }
    function sendCoin(address receiver, uint amount) public returns(bool sufficient) {
        if (balances[msg.sender] < amount) return false;
        balances[msg.sender]-= amount;
        balances[receiver] += amount;
        emit Transfer(msg.sender, receiver, amount);
        return true;
    }
    function getBalanceInEth(address addr) public view returns(uint){
        return ConvertLib.convert(getBalance(addr),2);
    }
    function getBalance(address addr) public view returns(uint) {
        return balances[addr];
    }
}
除了构造函数之外,这个合约还有3个方法( sendCoingetBalanceInEthgetBalance)。这3个方法都可以作为交易或调用执行。
现在让我们看看Truffle提供的Javascripe对象MetaCoin,可以在Truffle控制台中,调用 deployed()返回合约抽象对象:
truffle(develop)> let instance = await MetaCoin.deployed() //返回合约抽象对象
truffle(develop)> instance
// outputs:
//
// Contract
//-address: "0xa9f441a487754e6b27ba044a5a8eb2eec77f6b92"
//-allEvents: ()
//-getBalance: ()
//-getBalanceInEth: ()
//-sendCoin: ()
// ...
注意,合约抽象包含了合约中存在的相同函数。它还包含MetaCoin合约已部署版本的地址。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4