以太坊开发测试(4)原始案例分析 MetaCoin.sol

本文深入探讨了使用Truffle框架部署智能合约的过程,包括如何声明并链接库合约,如ConvertLib,以及部署主要合约,如MetaCoin。文章详细解释了MetaCoin合约中地址到余额的映射、转账事件的定义、构造函数的初始化、转账方法的实现以及如何使用库函数进行余额转换。

接着上一篇内容,我们继续分析truffle 给与的原始案例内容。

const ConvertLib = artifacts.require("ConvertLib"); //声明需要使用的合约1
const MetaCoin = artifacts.require("MetaCoin");     //声明需要使用的合约2

module.exports = function(deployer) {               //和之前一样,部署合约
  deployer.deploy(ConvertLib);                    
  deployer.link(ConvertLib, MetaCoin);  //link 连接方法,MetaCoin 需要依赖ConvertLib
  deployer.deploy(MetaCoin);
};

ConvertLib.sol 内容如下:

pragma solidity >=0.4.25 <0.7.0;

library ConvertLib{
        function convert(uint amount,uint conversionRate) public pure returns (uint convertedAmount)
        {
                return amount * conversionRate;
        }
}
library 是库函数的定义,我们可编写一些公共的库函数,声明为库,其他的合约可以直接调用库函数。

以上只是一个库函数的示例,我们直接进入看MetaCoin.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;
        }
       //构造函数,tx.origin 是一个全局变量,返回最初发送调用的账户地址。
        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;
        }//转账方法 emit 关键字用来触发事件

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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值