1. Crowdsale.sol:众筹合约

pragma solidity ^0.4.24;import "../token/ERC20/ERC20.sol";
import "../math/SafeMath.sol";
import "../token/ERC20/SafeERC20.sol";/*** @title Crowdsale* @dev Crowdsale is a base contract for managing a token crowdsale,* allowing investors to purchase tokens with ether. This contract implements* such functionality in its most fundamental form and can be extended to provide additional* functionality and/or custom behavior.* The external interface represents the basic interface for purchasing tokens, and conform* the base architecture for crowdsales. They are *not* intended to be modified / overridden.* The internal interface conforms the extensible and modifiable surface of crowdsales. Override* the methods to add functionality. Consider using 'super' where appropriate to concatenate* behavior.*/
contract Crowdsale {using SafeMath for uint256;using SafeERC20 for ERC20;// The token being soldERC20 public token; // 用于发型的TOKEN// Address where funds are collectedaddress public wallet; // 钱包地址,用于存储众筹所得的以太币// How many token units a buyer gets per wei.// The rate is the conversion between wei and the smallest and indivisible token unit.// So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK// 1 wei will give you 1 unit, or 0.001 TOK.uint256 public rate; // 和以太币的汇率兑换(以wei位基本单位)// Amount of wei raiseduint256 public weiRaised;/*** Event for token purchase logging* @param purchaser who paid for the tokens* @param beneficiary who got the tokens* @param value weis paid for purchase* @param amount amount of tokens purchased*/// 购买token的记录event TokenPurchase(address indexed purchaser, // 买家address indexed beneficiary, // 受益人uint256 value, // 费用uint256 amount // 购买的token数量);/*** @param _rate Number of token units a buyer gets per wei* @param _wallet Address where collected funds will be forwarded to* @param _token Address of the token being sold*/constructor(uint256 _rate, address _wallet, ERC20 _token) public {require(_rate > 0);require(_wallet != address(0));require(_token != address(0));rate = _rate;wallet = _wallet;token = _token;}// -----------------------------------------// Crowdsale external interface// -----------------------------------------/*** @dev fallback function ***DO NOT OVERRIDE****/function () external payable {buyTokens(msg.sender);}/*** @dev low level token purchase ***DO NOT OVERRIDE**** @param _beneficiary Address performing the token purchase*/// 买tokenfunction buyTokens(address _beneficiary) public payable {uint256 weiAmount = msg.value;_preValidatePurchase(_beneficiary, weiAmount);// calculate token amount to be createduint256 tokens = _getTokenAmount(weiAmount);// update stateweiRaised = weiRaised.add(weiAmount);_processPurchase(_beneficiary, tokens);emit TokenPurchase(msg.sender,_beneficiary,weiAmount,tokens);_updatePurchasingState(_beneficiary, weiAmount);_forwardFunds();_postValidatePurchase(_beneficiary, weiAmount);}// -----------------------------------------// Internal interface (extensible)// -----------------------------------------/*** @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.* Example from CappedCrowdsale.sol's _preValidatePurchase method: *   super._preValidatePurchase(_beneficiary, _weiAmount);*   require(weiRaised.add(_weiAmount) <= cap);* @param _beneficiary Address performing the token purchase* @param _weiAmount Value in wei involved in the purchase*/// 前置检查function _preValidatePurchase(address _beneficiary,uint256 _weiAmount)internal{require(_beneficiary != address(0));require(_weiAmount != 0);}/*** @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.* @param _beneficiary Address performing the token purchase* @param _weiAmount Value in wei involved in the purchase*/// 购买执行之后的验证,在条件不满足时,回滚状态function _postValidatePurchase(address _beneficiary,uint256 _weiAmount)internal{// optional override}/*** @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.* @param _beneficiary Address performing the token purchase* @param _tokenAmount Number of tokens to be emitted*/// 交互tokenfunction _deliverTokens(address _beneficiary,uint256 _tokenAmount)internal{token.safeTransfer(_beneficiary, _tokenAmount);}/*** @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.* @param _beneficiary Address receiving the tokens* @param _tokenAmount Number of tokens to be purchased*/function _processPurchase(address _beneficiary,uint256 _tokenAmount)internal{_deliverTokens(_beneficiary, _tokenAmount);}/*** @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)* @param _beneficiary Address receiving the tokens* @param _weiAmount Value in wei involved in the purchase*/function _updatePurchasingState(address _beneficiary,uint256 _weiAmount)internal{// optional override}/*** @dev Override to extend the way in which ether is converted to tokens.* @param _weiAmount Value in wei to be converted into tokens* @return Number of tokens that can be purchased with the specified _weiAmount*/// 获取到token数量function _getTokenAmount(uint256 _weiAmount)internal view returns (uint256){return _weiAmount.mul(rate);}/*** @dev Determines how ETH is stored/forwarded on purchases.*/// 确定购买是转发以太币function _forwardFunds() internal {wallet.transfer(msg.value);}
}

2. CappedCrowdsale.sol:众筹上限

pragma solidity ^0.4.24;import "../../math/SafeMath.sol";
import "../Crowdsale.sol";/*** @title CappedCrowdsale* @dev Crowdsale with a limit for total contributions.*/
// 众筹上限合约
contract CappedCrowdsale is Crowdsale {using SafeMath for uint256;uint256 public cap; // 众筹的上限/*** @dev Constructor, takes maximum amount of wei accepted in the crowdsale.* @param _cap Max amount of wei to be contributed*/constructor(uint256 _cap) public {require(_cap > 0);cap = _cap;}/*** @dev Checks whether the cap has been reached.* @return Whether the cap was reached*/// 检查众筹金额是否已经达到上限function capReached() public view returns (bool) {return weiRaised >= cap;}/*** @dev Extend parent behavior requiring purchase to respect the funding cap.* @param _beneficiary Token purchaser* @param _weiAmount Amount of wei contributed*/function _preValidatePurchase(address _beneficiary,uint256 _weiAmount)internal{super._preValidatePurchase(_beneficiary, _weiAmount);require(weiRaised.add(_weiAmount) <= cap);}}

3. IndividuallyCappedCrowdsale.sol:个人的众筹上限

pragma solidity ^0.4.24;import "../../math/SafeMath.sol";
import "../Crowdsale.sol";
import "../../ownership/Ownable.sol";/*** @title IndividuallyCappedCrowdsale* @dev Crowdsale with per-user caps.*/
// 每一个用的购买上限
contract IndividuallyCappedCrowdsale is Crowdsale, Ownable {using SafeMath for uint256;mapping(address => uint256) public contributions;mapping(address => uint256) public caps;/*** @dev Sets a specific user's maximum contribution.* @param _beneficiary Address to be capped* @param _cap Wei limit for individual contribution*/// 设置指定地址的上限function setUserCap(address _beneficiary, uint256 _cap) external onlyOwner {caps[_beneficiary] = _cap;}/*** @dev Sets a group of users' maximum contribution.* @param _beneficiaries List of addresses to be capped* @param _cap Wei limit for individual contribution*/// 为指定的地址集合设置相同的上限function setGroupCap(address[] _beneficiaries,uint256 _cap)externalonlyOwner{for (uint256 i = 0; i < _beneficiaries.length; i++) {caps[_beneficiaries[i]] = _cap;}}/*** @dev Returns the cap of a specific user.* @param _beneficiary Address whose cap is to be checked* @return Current cap for individual user*/// 返回指定地址的购买上限function getUserCap(address _beneficiary) public view returns (uint256) {return caps[_beneficiary];}/*** @dev Returns the amount contributed so far by a sepecific user.* @param _beneficiary Address of contributor* @return User contribution so far*/// 返回当前地址的购买量function getUserContribution(address _beneficiary)public view returns (uint256){return contributions[_beneficiary];}/*** @dev Extend parent behavior requiring purchase to respect the user's funding cap.* @param _beneficiary Token purchaser* @param _weiAmount Amount of wei contributed*/function _preValidatePurchase(address _beneficiary,uint256 _weiAmount)internal{super._preValidatePurchase(_beneficiary, _weiAmount);require(contributions[_beneficiary].add(_weiAmount) <= caps[_beneficiary]);}/*** @dev Extend parent behavior to update user contributions* @param _beneficiary Token purchaser* @param _weiAmount Amount of wei contributed*/// 更新当前地址的众筹量function _updatePurchasingState(address _beneficiary,uint256 _weiAmount)internal{super._updatePurchasingState(_beneficiary, _weiAmount);contributions[_beneficiary] = contributions[_beneficiary].add(_weiAmount);}}

4. TimedCrowdsale:众筹时间范围

pragma solidity ^0.4.24;import "../../math/SafeMath.sol";
import "../Crowdsale.sol";/*** @title TimedCrowdsale* @dev Crowdsale accepting contributions only within a time frame.*/
// 众筹时间范围
contract TimedCrowdsale is Crowdsale {using SafeMath for uint256;uint256 public openingTime; // 启动时间uint256 public closingTime; // 结束时间/*** @dev Reverts if not in crowdsale time range.*/modifier onlyWhileOpen {// solium-disable-next-line security/no-block-membersrequire(block.timestamp >= openingTime && block.timestamp <= closingTime);_;}/*** @dev Constructor, takes crowdsale opening and closing times.* @param _openingTime Crowdsale opening time* @param _closingTime Crowdsale closing time*/// 设置时间范围constructor(uint256 _openingTime, uint256 _closingTime) public {// solium-disable-next-line security/no-block-membersrequire(_openingTime >= block.timestamp);require(_closingTime >= _openingTime);openingTime = _openingTime;closingTime = _closingTime;}/*** @dev Checks whether the period in which the crowdsale is open has already elapsed.* @return Whether crowdsale period has elapsed*/// 检验众筹是否已经关闭function hasClosed() public view returns (bool) {// solium-disable-next-line security/no-block-membersreturn block.timestamp > closingTime;}/*** @dev Extend parent behavior requiring to be within contributing period* @param _beneficiary Token purchaser* @param _weiAmount Amount of wei contributed*/function _preValidatePurchase(address _beneficiary,uint256 _weiAmount)internalonlyWhileOpen{super._preValidatePurchase(_beneficiary, _weiAmount);}}

5.WhitelistedCrowdsale.sol:白名单

pragma solidity ^0.4.24;import "../Crowdsale.sol";
import "../../access/Whitelist.sol";/*** @title WhitelistedCrowdsale* @dev Crowdsale in which only whitelisted users can contribute.*/
// 可以参与众筹的白名单地址列表
contract WhitelistedCrowdsale is Whitelist, Crowdsale {/*** @dev Extend parent behavior requiring beneficiary to be in whitelist.* @param _beneficiary Token beneficiary* @param _weiAmount Amount of wei contributed*/function _preValidatePurchase(address _beneficiary,uint256 _weiAmount)internalonlyIfWhitelisted(_beneficiary){super._preValidatePurchase(_beneficiary, _weiAmount);}}

6. IncreasingPriceCrowdsale.sol:token价格变动

pragma solidity ^0.4.24;import "../validation/TimedCrowdsale.sol";
import "../../math/SafeMath.sol";/*** @title IncreasingPriceCrowdsale* @dev Extension of Crowdsale contract that increases the price of tokens linearly in time.* Note that what should be provided to the constructor is the initial and final _rates_, that is,* the amount of tokens per wei contributed. Thus, the initial rate must be greater than the final rate.*/
// 扩展的TOKEN合约,增加TOKEN价格
contract IncreasingPriceCrowdsale is TimedCrowdsale {using SafeMath for uint256;uint256 public initialRate;uint256 public finalRate;/*** @dev Constructor, takes initial and final rates of tokens received per wei contributed.* @param _initialRate Number of tokens a buyer gets per wei at the start of the crowdsale* @param _finalRate Number of tokens a buyer gets per wei at the end of the crowdsale*/constructor(uint256 _initialRate, uint256 _finalRate) public {require(_initialRate >= _finalRate);require(_finalRate > 0);initialRate = _initialRate;finalRate = _finalRate;}/*** @dev Returns the rate of tokens per wei at the present time.* Note that, as price _increases_ with time, the rate _decreases_.* @return The number of tokens a buyer gets per wei at a given time*/// 获取当前兑换率function getCurrentRate() public view returns (uint256) {// solium-disable-next-line security/no-block-membersuint256 elapsedTime = block.timestamp.sub(openingTime);uint256 timeRange = closingTime.sub(openingTime);uint256 rateRange = initialRate.sub(finalRate);return initialRate.sub(elapsedTime.mul(rateRange).div(timeRange));}/*** @dev Overrides parent method taking into account variable rate.* @param _weiAmount The value in wei to be converted into tokens* @return The number of tokens _weiAmount wei will buy at present time*/// 获取当前的token数量function _getTokenAmount(uint256 _weiAmount)internal view returns (uint256){uint256 currentRate = getCurrentRate();return currentRate.mul(_weiAmount);}}

7. RefundableCrowdsale.sol:退款

pragma solidity ^0.4.24;import "../../math/SafeMath.sol";
import "./FinalizableCrowdsale.sol";
import "../../payment/RefundEscrow.sol";/*** @title RefundableCrowdsale* @dev Extension of Crowdsale contract that adds a funding goal, and* the possibility of users getting a refund if goal is not met.*/
// 扩展合约,增加资金目标,或者在未达到目标是支持用户退块
contract RefundableCrowdsale is FinalizableCrowdsale {using SafeMath for uint256;// minimum amount of funds to be raised in weisuint256 public goal;// refund escrow used to hold funds while crowdsale is runningRefundEscrow private escrow;/*** @dev Constructor, creates RefundEscrow.* @param _goal Funding goal*/constructor(uint256 _goal) public {require(_goal > 0);escrow = new RefundEscrow(wallet);goal = _goal;}/*** @dev Investors can claim refunds here if crowdsale is unsuccessful*/function claimRefund() public {require(isFinalized);require(!goalReached());escrow.withdraw(msg.sender);}/*** @dev Checks whether funding goal was reached.* @return Whether funding goal was reached*/function goalReached() public view returns (bool) {return weiRaised >= goal;}/*** @dev escrow finalization task, called when owner calls finalize()*/function finalization() internal {if (goalReached()) {escrow.close();escrow.beneficiaryWithdraw();} else {escrow.enableRefunds();}super.finalization();}/*** @dev Overrides Crowdsale fund forwarding, sending funds to escrow.*/function _forwardFunds() internal {escrow.deposit.value(msg.value)(msg.sender);}}

8. PostDeliveryCrowdsale.sol:锁仓

pragma solidity ^0.4.24;import "../validation/TimedCrowdsale.sol";
import "../../token/ERC20/ERC20.sol";
import "../../math/SafeMath.sol";/*** @title PostDeliveryCrowdsale* @dev Crowdsale that locks tokens from withdrawal until it ends.*/// 锁定TOKEN(锁仓)
contract PostDeliveryCrowdsale is TimedCrowdsale {using SafeMath for uint256;mapping(address => uint256) public balances;/*** @dev Withdraw tokens only after crowdsale ends.*/function withdrawTokens() public {require(hasClosed());uint256 amount = balances[msg.sender];require(amount > 0);balances[msg.sender] = 0;_deliverTokens(msg.sender, amount);}/*** @dev Overrides parent by storing balances instead of issuing tokens right away.* @param _beneficiary Token purchaser* @param _tokenAmount Amount of tokens purchased*/function _processPurchase(address _beneficiary,uint256 _tokenAmount)internal{balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount);}}

9. FinalizableCrowdsale.sol:众筹完成之后的操作

pragma solidity ^0.4.24;import "../../math/SafeMath.sol";
import "../../ownership/Ownable.sol";
import "../validation/TimedCrowdsale.sol";/*** @title FinalizableCrowdsale* @dev Extension of Crowdsale where an owner can do extra work* after finishing.*/
// 在完成众筹之后所进行的额外操作
contract FinalizableCrowdsale is TimedCrowdsale, Ownable {using SafeMath for uint256;bool public isFinalized = false;event Finalized();/*** @dev Must be called after crowdsale ends, to do some extra finalization* work. Calls the contract's finalization function.*/function finalize() public onlyOwner {require(!isFinalized);require(hasClosed());finalization();emit Finalized();isFinalized = true;}/*** @dev Can be overridden to add finalization logic. The overriding function* should call super.finalization() to ensure the chain of finalization is* executed entirely.*/function finalization() internal {}}

Openzeppelin库 09.Crowdsale相关推荐

  1. Openzeppelin库第八期:Crowdsale

    Crowdsale.sol:众筹合约 pragma solidity ^0.4.24;import "../token/ERC20/ERC20.sol"; import " ...

  2. 2023 华为 Datacom-HCIE 真题题库 09/12--含解析

    单项选择题 1.[试题编号:190485] (单选题)华为交换机MAC地址表的老化时间默认是多少秒? A.500 B.5 C.300 D.400 答案:C 解析:无 2.[试题编号:190484] ( ...

  3. zeppelin连接数据源_使用开放源代码合同(open-zeppelin)创建以太坊令牌

    zeppelin连接数据源 by Danny 通过丹尼 使用开放源代码合同(open-zeppelin)创建以太坊令牌 (Create an Ethereum token using open sou ...

  4. 使用OpenZeppelin在RSK上进行ERC20代币开发

    在本文中,我们将讨论通过RSK网络部署和交互Smart-Contracts智能合约.我们的合约将是一个基于OpenZeppelin库的ERC20代币,我们将把它直接部署到Mainnet中. 创建合约 ...

  5. 用OpenZeppelin在RSK上进行以太坊ERC20代币开发

    在本文中,我们将讨论通过RSK网络部署和交互Smart-Contracts智能合约.我们的合约将是一个基于OpenZeppelin库的ERC20代币,我们将把它直接部署到Mainnet中. 创建合约 ...

  6. 解决“@openzeppelin/contracts/proxy/ not find“问题

        今天在slither测试智能合约时,发现"@openzeppelin/contracts/proxy " File not found问题,如图(1)所示. 图(1) sl ...

  7. CentOS6.3编译安装Nginx1.4.7 + MySQL5.5.25a + PHP5.3.28

    2019独角兽企业重金招聘Python工程师标准>>> [准备工作] 01 #在编译安装lnmp之前,首先先卸载已存在的rpm包. 02 rpm -e httpd 03 rpm -e ...

  8. 十一课堂|通过小游戏学习Ethereum DApps编程(4)

    2019独角兽企业重金招聘Python工程师标准>>> 在上篇完结的时候,我们制造出了这个独一无二可爱至极的角色: 这里我们继续总结一些关于solidity语言的知识点.并且开始了解 ...

  9. 删除隐藏版本信息 版本回退_Git系列之-分布式版本控制Git详解

    课程简介: 课程目标:通过本课程的学习,将全面掌握Git版本管理工具的配置与使用,以适应工作的需要. 适用人群:具有一定开发基础的开发人员. 课程概述:Git (读音为/gɪt/)是一个开源的分布式版 ...

最新文章

  1. 关注点分离之RestTemplate的错误处理
  2. 别再说你不会!自学java教程百度云
  3. JS闭包的理解及常见应用场景
  4. 【转】ubuntu16.04安装配置tftp服务
  5. JavaWeb笔记05-解决线程安全问题
  6. 基于动态混合高斯模型的商品价格模型算法
  7. 熊猫concat()例子
  8. mysql router 多台写入_Centos7部署MySQL-router实现读写分离及从库负载均衡
  9. html css实验6,(实验六DivCSS网页布局.doc
  10. bootstrap-multiselect.js插件、chosen插件、clipboard复制插件、layer.photos、lightbox插件相册预览插件学习
  11. 如何计算虚拟化vcpu_【科普】CPU和内存虚拟化
  12. POJ——多项式加法(WA)
  13. java 排列组合算法_关于各种排列组合java算法
  14. excel未保存强制关闭计算机,Excel文件未保存就关闭了,怎么恢复数据?
  15. luogu P3975 [TJOI2015]弦论 SAM
  16. 【dva】dva使用与实现(一)
  17. 伤寒杂病论.辨太阳病脉证并治(中)
  18. FTP服务器的配置,以及配置ftp支持ftps
  19. AlphaFold2源码解析(4)--模型架构
  20. mysql用int做时间戳存储,最大2147483647, 大限2038年

热门文章

  1. Python 实现远程监控中心
  2. SVN异常处理——禁止访问
  3. Android adb shell后面可用的常用命令详细列举
  4. [在线挑战]【i春秋】渗透测试入门 —— 渗透测试笔记 --转
  5. 螺旋图形Linux,一个实例带你熟练使用UG中的螺旋线,新手必备!
  6. Ceph配置——5.Ceph-MON设置
  7. 格林尼治标准时(GMT)与世界时(UTC)
  8. python工资一般多少p-我会P图,工资5000,兼职1.5w……
  9. 第12周前端学习周报
  10. python 绕过国科大教务系统获取所有学生成绩