• 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);}
}
  • 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);}}
  • 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);}}
  • 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);}}
  • 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);}}
  • 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);}}
  • 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);}}
  • 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);}}
  • 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库第八期:Crowdsale相关推荐

  1. android 周报,MAndroid 周报第八期

    MAndroid 周报第八期 写在前面的话 大家补充的库 一.开源库 简单好用的ratingbar image RecyclerView下拉刷新,自动加载更多:仿IOS侧滑Item删除菜单 image ...

  2. 第八期杭州NodeParty x Rokid技术分享会回顾

    12 月 9 号,杭州 NodeParty 和 Rokid 联合主办的第八期技术分享会,在 Rokid公司如期举行.虽然是下雪天,但各位程序猿大大对 Node.js 的热情不减,准时赴约. 整场分享持 ...

  3. DC 视频教程 第八期

    第八期 Timing Analysis DC仅能把RTL代码翻译成原理图,综合之后还需要检查综合后的电路是否能够使用. 除了DC内部嵌入的时序分析软件以外,PrimeTime可以进行权威.全面的时序检 ...

  4. datawhale_爬虫_spider |第八期

    文章目录 task01 任务预览 code_datawhale01_douban_top250 result task02 任务预览 code_datawhale02-01_dxybbs_reply_ ...

  5. COS访谈第十八期:陈天奇

    COS访谈第十八期:陈天奇 [COS编辑部按] 受访者:陈天奇      采访者:何通   编辑:王小宁 简介:陈天奇,华盛顿大学计算机系博士生,研究方向为大规模机器学习.他曾获得KDD CUP 20 ...

  6. C++_泛型编程与标准库(八)

    C++_泛型编程与标准库(八) 参考:<侯捷泛化编程与标准库>.GNU9.3.0,vs2019 图中标红部分为自己的笔记理解 1.array GNU 2.9的写法 array GNU9.3 ...

  7. 写在马哥教育第八期开始之前

    "你不能剥夺别人思考的权力"!记得读研期间一位导师在谈到"传道.授业.解惑"时特地强调.当时身为学生,并未能完全.真切地理解这位导师表述的真正意图.而当自己独立 ...

  8. 信息安全意识电子期刊第八期

    2019独角兽企业重金招聘Python工程师标准>>> 信息安全意识电子期刊第八期 网购热潮兴起,支付安全备受关注.虽然网上支付快捷方便,但是仍存在着很多的安全隐患,账户里的钱被莫名 ...

  9. 推荐八款来自极客标签的超棒前端特效[第八期]

    为什么80%的码农都做不了架构师?>>>    日期:2013-6-24  来源:GBin1.com 本周,我们带来了极客社区推荐的10款前端特效,非常有趣的小游戏和页面生成.希望可 ...

最新文章

  1. [Vert.x Core手册 for Java]-了解Vert.x
  2. python软件管理系统_conda:基于python的软件管理系统
  3. Java集合篇:ArrayList详解
  4. 最牛营业部——国信泰然九路揭秘
  5. 解决ios上微信无法捕获返回键按钮事件的问题
  6. 落地即王道,锁死企业智变CP——云+AI
  7. Install Kernel 3.10 on CentOS 6.5
  8. 在Dynamics 365 Fo/AX2012中获取不同类型的时间
  9. 神经网络之智能科学与技术专业
  10. 无线通信设备安装工程概预算编制_南宁市轨道交通5号线一期工程专用无线通信系统设备采购...
  11. PLSQL14下载与安装及使用
  12. 赛门铁克并购 Blue Coat 的益处显现
  13. angularjs 猜大小
  14. tab标签页-选项卡后边+后端所返数据的数量
  15. 史玉柱论民营企业的“13种死法”
  16. 新版QQ功能录制屏幕、截取任意形状、屏幕文字识别
  17. iostat命令详解指标分析
  18. 关于 苏生不惑 公众号
  19. 初识fastAdmin表格列表的功能
  20. 加缪:人生无意义且荒诞

热门文章

  1. 使用c++开发excel插件 (第3章动态链接库(dynamic-link library))
  2. 超好的数据结构算法可视化网站
  3. 浙大pythonpta作业答案_浙大PTA-Python题库 编程题第一章(1-1~1-3)题解
  4. 非常全面的数字人解决方案(含源码)
  5. 扫码登录的原理和实现
  6. linux的命令参考手册,Linux常用命令汇总——可当作简要参考手册 - 程序语言 - 小木虫 - 学术 科研 互动社区...
  7. 2017 LARS:LARGE BATCH TRAINING OF CONVOLUTIONAL NETWORKS (训练大Batch的卷积神经网络)
  8. r语言nonzerocoef函数_lars算法R语言操作指南.pdf
  9. 这样创建EC2实例,才算没浪费AWS的一年免费套餐
  10. 【BI学习心得10-时间序列实战】