接着上一篇内容,我们继续分析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];
}
}
本文深入探讨了使用Truffle框架部署智能合约的过程,包括如何声明并链接库合约,如ConvertLib,以及部署主要合约,如MetaCoin。文章详细解释了MetaCoin合约中地址到余额的映射、转账事件的定义、构造函数的初始化、转账方法的实现以及如何使用库函数进行余额转换。
786

被折叠的 条评论
为什么被折叠?



