1. pragma solidity ^0.5.0;
  2. /**
  3. * @dev Interface of the ERC20 standard as defined in the EIP. Does not include
  4. * the optional functions; to access them see {ERC20Detailed}.
  5. */
  6. interface IERC20 {
  7. /**
  8. * @dev Returns the amount of tokens in existence.
  9. */
  10. function totalSupply() external view returns (uint256);
  11. /**
  12. * @dev Returns the amount of tokens owned by `account`.
  13. */
  14. function balanceOf(address account) external view returns (uint256);
  15. /**
  16. * @dev Moves `amount` tokens from the caller's account to `recipient`.
  17. *
  18. * Returns a boolean value indicating whether the operation succeeded.
  19. *
  20. * Emits a {Transfer} event.
  21. */
  22. function transfer(address recipient, uint256 amount) external returns (bool);
  23. /**
  24. * @dev Returns the remaining number of tokens that `spender` will be
  25. * allowed to spend on behalf of `owner` through {transferFrom}. This is
  26. * zero by default.
  27. *
  28. * This value changes when {approve} or {transferFrom} are called.
  29. */
  30. function allowance(address owner, address spender) external view returns (uint256);
  31. /**
  32. * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
  33. *
  34. * Returns a boolean value indicating whether the operation succeeded.
  35. *
  36. * IMPORTANT: Beware that changing an allowance with this method brings the risk
  37. * that someone may use both the old and the new allowance by unfortunate
  38. * transaction ordering. One possible solution to mitigate this race
  39. * condition is to first reduce the spender's allowance to 0 and set the
  40. * desired value afterwards:
  41. * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
  42. *
  43. * Emits an {Approval} event.
  44. */
  45. function approve(address spender, uint256 amount) external returns (bool);
  46. /**
  47. * @dev Moves `amount` tokens from `sender` to `recipient` using the
  48. * allowance mechanism. `amount` is then deducted from the caller's
  49. * allowance.
  50. *
  51. * Returns a boolean value indicating whether the operation succeeded.
  52. *
  53. * Emits a {Transfer} event.
  54. */
  55. function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
  56. /**
  57. * @dev Emitted when `value` tokens are moved from one account (`from`) to
  58. * another (`to`).
  59. *
  60. * Note that `value` may be zero.
  61. */
  62. event Transfer(address indexed from, address indexed to, uint256 value);
  63. /**
  64. * @dev Emitted when the allowance of a `spender` for an `owner` is set by
  65. * a call to {approve}. `value` is the new allowance.
  66. */
  67. event Approval(address indexed owner, address indexed spender, uint256 value);
  68. }
  69. pragma solidity ^0.5.0;
  70. /**
  71. * @dev Contract module that helps prevent reentrant calls to a function.
  72. *
  73. * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
  74. * available, which can be applied to functions to make sure there are no nested
  75. * (reentrant) calls to them.
  76. *
  77. * Note that because there is a single `nonReentrant` guard, functions marked as
  78. * `nonReentrant` may not call one another. This can be worked around by making
  79. * those functions `private`, and then adding `external` `nonReentrant` entry
  80. * points to them.
  81. *
  82. * _Since v2.5.0:_ this module is now much more gas efficient, given net gas
  83. * metering changes introduced in the Istanbul hardfork.
  84. */
  85. contract ReentrancyGuard {
  86. bool private _notEntered;
  87. constructor () internal {
  88. // Storing an initial non-zero value makes deployment a bit more
  89. // expensive, but in exchange the refund on every call to nonReentrant
  90. // will be lower in amount. Since refunds are capped to a percetange of
  91. // the total transaction's gas, it is best to keep them low in cases
  92. // like this one, to increase the likelihood of the full refund coming
  93. // into effect.
  94. _notEntered = true;
  95. }
  96. /**
  97. * @dev Prevents a contract from calling itself, directly or indirectly.
  98. * Calling a `nonReentrant` function from another `nonReentrant`
  99. * function is not supported. It is possible to prevent this from happening
  100. * by making the `nonReentrant` function external, and make it call a
  101. * `private` function that does the actual work.
  102. */
  103. modifier nonReentrant() {
  104. // On the first call to nonReentrant, _notEntered will be true
  105. require(_notEntered, "ReentrancyGuard: reentrant call");
  106. // Any calls to nonReentrant after this point will fail
  107. _notEntered = false;
  108. _;
  109. // By storing the original value once again, a refund is triggered (see
  110. // https://eips.ethereum.org/EIPS/eip-2200)
  111. _notEntered = true;
  112. }
  113. }
  114. pragma solidity ^0.5.0;
  115. /*
  116. * @dev Provides information about the current execution context, including the
  117. * sender of the transaction and its data. While these are generally available
  118. * via msg.sender and msg.data, they should not be accessed in such a direct
  119. * manner, since when dealing with GSN meta-transactions the account sending and
  120. * paying for execution may not be the actual sender (as far as an application
  121. * is concerned).
  122. *
  123. * This contract is only required for intermediate, library-like contracts.
  124. */
  125. contract Context {
  126. // Empty internal constructor, to prevent people from mistakenly deploying
  127. // an instance of this contract, which should be used via inheritance.
  128. constructor () internal { }
  129. // solhint-disable-previous-line no-empty-blocks
  130. function _msgSender() internal view returns (address payable) {
  131. return msg.sender;
  132. }
  133. function _msgData() internal view returns (bytes memory) {
  134. this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
  135. return msg.data;
  136. }
  137. }
  138. pragma solidity ^0.5.0;
  139. /**
  140. * @dev Wrappers over Solidity's arithmetic operations with added overflow
  141. * checks.
  142. *
  143. * Arithmetic operations in Solidity wrap on overflow. This can easily result
  144. * in bugs, because programmers usually assume that an overflow raises an
  145. * error, which is the standard behavior in high level programming languages.
  146. * `SafeMath` restores this intuition by reverting the transaction when an
  147. * operation overflows.
  148. *
  149. * Using this library instead of the unchecked operations eliminates an entire
  150. * class of bugs, so it's recommended to use it always.
  151. */
  152. library SafeMath {
  153. /**
  154. * @dev Returns the addition of two unsigned integers, reverting on
  155. * overflow.
  156. *
  157. * Counterpart to Solidity's `+` operator.
  158. *
  159. * Requirements:
  160. * - Addition cannot overflow.
  161. */
  162. function add(uint256 a, uint256 b) internal pure returns (uint256) {
  163. uint256 c = a + b;
  164. require(c >= a, "SafeMath: addition overflow");
  165. return c;
  166. }
  167. /**
  168. * @dev Returns the subtraction of two unsigned integers, reverting on
  169. * overflow (when the result is negative).
  170. *
  171. * Counterpart to Solidity's `-` operator.
  172. *
  173. * Requirements:
  174. * - Subtraction cannot overflow.
  175. */
  176. function sub(uint256 a, uint256 b) internal pure returns (uint256) {
  177. return sub(a, b, "SafeMath: subtraction overflow");
  178. }
  179. /**
  180. * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
  181. * overflow (when the result is negative).
  182. *
  183. * Counterpart to Solidity's `-` operator.
  184. *
  185. * Requirements:
  186. * - Subtraction cannot overflow.
  187. *
  188. * _Available since v2.4.0._
  189. */
  190. function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
  191. require(b <= a, errorMessage);
  192. uint256 c = a - b;
  193. return c;
  194. }
  195. /**
  196. * @dev Returns the multiplication of two unsigned integers, reverting on
  197. * overflow.
  198. *
  199. * Counterpart to Solidity's `*` operator.
  200. *
  201. * Requirements:
  202. * - Multiplication cannot overflow.
  203. */
  204. function mul(uint256 a, uint256 b) internal pure returns (uint256) {
  205. // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
  206. // benefit is lost if 'b' is also tested.
  207. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
  208. if (a == 0) {
  209. return 0;
  210. }
  211. uint256 c = a * b;
  212. require(c / a == b, "SafeMath: multiplication overflow");
  213. return c;
  214. }
  215. /**
  216. * @dev Returns the integer division of two unsigned integers. Reverts on
  217. * division by zero. The result is rounded towards zero.
  218. *
  219. * Counterpart to Solidity's `/` operator. Note: this function uses a
  220. * `revert` opcode (which leaves remaining gas untouched) while Solidity
  221. * uses an invalid opcode to revert (consuming all remaining gas).
  222. *
  223. * Requirements:
  224. * - The divisor cannot be zero.
  225. */
  226. function div(uint256 a, uint256 b) internal pure returns (uint256) {
  227. return div(a, b, "SafeMath: division by zero");
  228. }
  229. /**
  230. * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
  231. * division by zero. The result is rounded towards zero.
  232. *
  233. * Counterpart to Solidity's `/` operator. Note: this function uses a
  234. * `revert` opcode (which leaves remaining gas untouched) while Solidity
  235. * uses an invalid opcode to revert (consuming all remaining gas).
  236. *
  237. * Requirements:
  238. * - The divisor cannot be zero.
  239. *
  240. * _Available since v2.4.0._
  241. */
  242. function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
  243. // Solidity only automatically asserts when dividing by 0
  244. require(b > 0, errorMessage);
  245. uint256 c = a / b;
  246. // assert(a == b * c + a % b); // There is no case in which this doesn't hold
  247. return c;
  248. }
  249. /**
  250. * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
  251. * Reverts when dividing by zero.
  252. *
  253. * Counterpart to Solidity's `%` operator. This function uses a `revert`
  254. * opcode (which leaves remaining gas untouched) while Solidity uses an
  255. * invalid opcode to revert (consuming all remaining gas).
  256. *
  257. * Requirements:
  258. * - The divisor cannot be zero.
  259. */
  260. function mod(uint256 a, uint256 b) internal pure returns (uint256) {
  261. return mod(a, b, "SafeMath: modulo by zero");
  262. }
  263. /**
  264. * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
  265. * Reverts with custom message when dividing by zero.
  266. *
  267. * Counterpart to Solidity's `%` operator. This function uses a `revert`
  268. * opcode (which leaves remaining gas untouched) while Solidity uses an
  269. * invalid opcode to revert (consuming all remaining gas).
  270. *
  271. * Requirements:
  272. * - The divisor cannot be zero.
  273. *
  274. * _Available since v2.4.0._
  275. */
  276. function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
  277. require(b != 0, errorMessage);
  278. return a % b;
  279. }
  280. }
  281. pragma solidity ^0.5.0;
  282. /**
  283. * @title SafeERC20
  284. * @dev Wrappers around ERC20 operations that throw on failure (when the token
  285. * contract returns false). Tokens that return no value (and instead revert or
  286. * throw on failure) are also supported, non-reverting calls are assumed to be
  287. * successful.
  288. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
  289. * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
  290. */
  291. library SafeERC20 {
  292. using SafeMath for uint256;
  293. using Address for address;
  294. function safeTransfer(IERC20 token, address to, uint256 value) internal {
  295. callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
  296. }
  297. function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
  298. callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
  299. }
  300. function safeApprove(IERC20 token, address spender, uint256 value) internal {
  301. // safeApprove should only be called when setting an initial allowance,
  302. // or when resetting it to zero. To increase and decrease it, use
  303. // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
  304. // solhint-disable-next-line max-line-length
  305. require((value == 0) || (token.allowance(address(this), spender) == 0),
  306. "SafeERC20: approve from non-zero to non-zero allowance"
  307. );
  308. callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
  309. }
  310. function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
  311. uint256 newAllowance = token.allowance(address(this), spender).add(value);
  312. callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
  313. }
  314. function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
  315. uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
  316. callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
  317. }
  318. /**
  319. * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
  320. * on the return value: the return value is optional (but if data is returned, it must not be false).
  321. * @param token The token targeted by the call.
  322. * @param data The call data (encoded using abi.encode or one of its variants).
  323. */
  324. function callOptionalReturn(IERC20 token, bytes memory data) private {
  325. // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
  326. // we're implementing it ourselves.
  327. // A Solidity high level call has three parts:
  328. // 1. The target address is checked to verify it contains contract code
  329. // 2. The call itself is made, and success asserted
  330. // 3. The return value is decoded, which in turn checks the size of the returned data.
  331. // solhint-disable-next-line max-line-length
  332. require(address(token).isContract(), "SafeERC20: call to non-contract");
  333. // solhint-disable-next-line avoid-low-level-calls
  334. (bool success, bytes memory returndata) = address(token).call(data);
  335. require(success, "SafeERC20: low-level call failed");
  336. if (returndata.length > 0) { // Return data is optional
  337. // solhint-disable-next-line max-line-length
  338. require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
  339. }
  340. }
  341. }
  342. pragma solidity ^0.5.0;
  343. /**
  344. * @dev Standard math utilities missing in the Solidity language.
  345. */
  346. library Math {
  347. /**
  348. * @dev Returns the largest of two numbers.
  349. */
  350. function max(uint256 a, uint256 b) internal pure returns (uint256) {
  351. return a >= b ? a : b;
  352. }
  353. /**
  354. * @dev Returns the smallest of two numbers.
  355. */
  356. function min(uint256 a, uint256 b) internal pure returns (uint256) {
  357. return a < b ? a : b;
  358. }
  359. /**
  360. * @dev Returns the average of two numbers. The result is rounded towards
  361. * zero.
  362. */
  363. function average(uint256 a, uint256 b) internal pure returns (uint256) {
  364. // (a + b) / 2 can overflow, so we distribute
  365. return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
  366. }
  367. }
  368. pragma solidity ^0.5.0;
  369. /**
  370. * @title Crowdsale
  371. * @dev Crowdsale is a base contract for managing a token crowdsale,
  372. * allowing investors to purchase tokens with ether. This contract implements
  373. * such functionality in its most fundamental form and can be extended to provide additional
  374. * functionality and/or custom behavior.
  375. * The external interface represents the basic interface for purchasing tokens, and conforms
  376. * the base architecture for crowdsales. It is *not* intended to be modified / overridden.
  377. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override
  378. * the methods to add functionality. Consider using 'super' where appropriate to concatenate
  379. * behavior.
  380. */
  381. contract Crowdsale is Context, ReentrancyGuard {
  382. using SafeMath for uint256;
  383. using SafeERC20 for IERC20;
  384. // The token being sold
  385. IERC20 private _token;
  386. // Address where funds are collected
  387. address payable private _wallet;
  388. // How many token units a buyer gets per wei.
  389. // The rate is the conversion between wei and the smallest and indivisible token unit.
  390. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
  391. // 1 wei will give you 1 unit, or 0.001 TOK.
  392. uint256 private _rate;
  393. // Amount of wei raised
  394. uint256 private _weiRaised;
  395. /**
  396. * Event for token purchase logging
  397. * @param purchaser who paid for the tokens
  398. * @param beneficiary who got the tokens
  399. * @param value weis paid for purchase
  400. * @param amount amount of tokens purchased
  401. */
  402. event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
  403. /**
  404. * @param rate Number of token units a buyer gets per wei
  405. * @dev The rate is the conversion between wei and the smallest and indivisible
  406. * token unit. So, if you are using a rate of 1 with a ERC20Detailed token
  407. * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
  408. * @param wallet Address where collected funds will be forwarded to
  409. * @param token Address of the token being sold
  410. */
  411. constructor (uint256 rate, address payable wallet, IERC20 token) public {
  412. require(rate > 0, "Crowdsale: rate is 0");
  413. require(wallet != address(0), "Crowdsale: wallet is the zero address");
  414. require(address(token) != address(0), "Crowdsale: token is the zero address");
  415. _rate = rate;
  416. _wallet = wallet;
  417. _token = token;
  418. }
  419. /**
  420. * @dev fallback function ***DO NOT OVERRIDE***
  421. * Note that other contracts will transfer funds with a base gas stipend
  422. * of 2300, which is not enough to call buyTokens. Consider calling
  423. * buyTokens directly when purchasing tokens from a contract.
  424. */
  425. function () external payable {
  426. buyTokens(_msgSender());
  427. }
  428. /**
  429. * @return the token being sold.
  430. */
  431. function token() public view returns (IERC20) {
  432. return _token;
  433. }
  434. /**
  435. * @return the address where funds are collected.
  436. */
  437. function wallet() public view returns (address payable) {
  438. return _wallet;
  439. }
  440. /**
  441. * @return the number of token units a buyer gets per wei.
  442. */
  443. function rate() public view returns (uint256) {
  444. return _rate;
  445. }
  446. /**
  447. * @return the amount of wei raised.
  448. */
  449. function weiRaised() public view returns (uint256) {
  450. return _weiRaised;
  451. }
  452. /**
  453. * @dev low level token purchase ***DO NOT OVERRIDE***
  454. * This function has a non-reentrancy guard, so it shouldn't be called by
  455. * another `nonReentrant` function.
  456. * @param beneficiary Recipient of the token purchase
  457. */
  458. function buyTokens(address beneficiary) public nonReentrant payable {
  459. uint256 weiAmount = msg.value;
  460. _preValidatePurchase(beneficiary, weiAmount);
  461. // calculate token amount to be created
  462. uint256 tokens = _getTokenAmount(weiAmount);
  463. // update state
  464. _weiRaised = _weiRaised.add(weiAmount);
  465. _processPurchase(beneficiary, tokens);
  466. emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens);
  467. _updatePurchasingState(beneficiary, weiAmount);
  468. _forwardFunds();
  469. _postValidatePurchase(beneficiary, weiAmount);
  470. }
  471. /**
  472. * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
  473. * Use `super` in contracts that inherit from Crowdsale to extend their validations.
  474. * Example from CappedCrowdsale.sol's _preValidatePurchase method:
  475. * super._preValidatePurchase(beneficiary, weiAmount);
  476. * require(weiRaised().add(weiAmount) <= cap);
  477. * @param beneficiary Address performing the token purchase
  478. * @param weiAmount Value in wei involved in the purchase
  479. */
  480. function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
  481. require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
  482. require(weiAmount != 0, "Crowdsale: weiAmount is 0");
  483. this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
  484. }
  485. /**
  486. * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
  487. * conditions are not met.
  488. * @param beneficiary Address performing the token purchase
  489. * @param weiAmount Value in wei involved in the purchase
  490. */
  491. function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
  492. // solhint-disable-previous-line no-empty-blocks
  493. }
  494. /**
  495. * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
  496. * its tokens.
  497. * @param beneficiary Address performing the token purchase
  498. * @param tokenAmount Number of tokens to be emitted
  499. */
  500. function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
  501. _token.safeTransfer(beneficiary, tokenAmount);
  502. }
  503. /**
  504. * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
  505. * tokens.
  506. * @param beneficiary Address receiving the tokens
  507. * @param tokenAmount Number of tokens to be purchased
  508. */
  509. function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
  510. _deliverTokens(beneficiary, tokenAmount);
  511. }
  512. /**
  513. * @dev Override for extensions that require an internal state to check for validity (current user contributions,
  514. * etc.)
  515. * @param beneficiary Address receiving the tokens
  516. * @param weiAmount Value in wei involved in the purchase
  517. */
  518. function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
  519. // solhint-disable-previous-line no-empty-blocks
  520. }
  521. /**
  522. * @dev Override to extend the way in which ether is converted to tokens.
  523. * @param weiAmount Value in wei to be converted into tokens
  524. * @return Number of tokens that can be purchased with the specified _weiAmount
  525. */
  526. function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
  527. return weiAmount.mul(_rate);
  528. }
  529. /**
  530. * @dev Determines how ETH is stored/forwarded on purchases.
  531. */
  532. function _forwardFunds() internal {
  533. _wallet.transfer(msg.value);
  534. }
  535. }
  536. pragma solidity ^0.5.0;
  537. /**
  538. * @title AllowanceCrowdsale
  539. * @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale.
  540. */
  541. contract AllowanceCrowdsale is Crowdsale {
  542. using SafeMath for uint256;
  543. using SafeERC20 for IERC20;
  544. address private _tokenWallet;
  545. /**
  546. * @dev Constructor, takes token wallet address.
  547. * @param tokenWallet Address holding the tokens, which has approved allowance to the crowdsale.
  548. */
  549. constructor (address tokenWallet) public {
  550. require(tokenWallet != address(0), "AllowanceCrowdsale: token wallet is the zero address");
  551. _tokenWallet = tokenWallet;
  552. }
  553. /**
  554. * @return the address of the wallet that will hold the tokens.
  555. */
  556. function tokenWallet() public view returns (address) {
  557. return _tokenWallet;
  558. }
  559. /**
  560. * @dev Checks the amount of tokens left in the allowance.
  561. * @return Amount of tokens left in the allowance
  562. */
  563. function remainingTokens() public view returns (uint256) {
  564. return Math.min(token().balanceOf(_tokenWallet), token().allowance(_tokenWallet, address(this)));
  565. }
  566. /**
  567. * @dev Overrides parent behavior by transferring tokens from wallet.
  568. * @param beneficiary Token purchaser
  569. * @param tokenAmount Amount of tokens purchased
  570. */
  571. function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
  572. token().safeTransferFrom(_tokenWallet, beneficiary, tokenAmount);
  573. }
  574. }
  575. pragma solidity ^0.5.0;
  576. /**
  577. * @title TimedCrowdsale
  578. * @dev Crowdsale accepting contributions only within a time frame.
  579. */
  580. contract TimedCrowdsale is Crowdsale {
  581. using SafeMath for uint256;
  582. uint256 private _openingTime;
  583. uint256 private _closingTime;
  584. /**
  585. * Event for crowdsale extending
  586. * @param newClosingTime new closing time
  587. * @param prevClosingTime old closing time
  588. */
  589. event TimedCrowdsaleExtended(uint256 prevClosingTime, uint256 newClosingTime);
  590. /**
  591. * @dev Reverts if not in crowdsale time range.
  592. */
  593. modifier onlyWhileOpen {
  594. require(isOpen(), "TimedCrowdsale: not open");
  595. _;
  596. }
  597. /**
  598. * @dev Constructor, takes crowdsale opening and closing times.
  599. * @param openingTime Crowdsale opening time
  600. * @param closingTime Crowdsale closing time
  601. */
  602. constructor (uint256 openingTime, uint256 closingTime) public {
  603. // solhint-disable-next-line not-rely-on-time
  604. require(openingTime >= block.timestamp, "TimedCrowdsale: opening time is before current time");
  605. // solhint-disable-next-line max-line-length
  606. require(closingTime > openingTime, "TimedCrowdsale: opening time is not before closing time");
  607. _openingTime = openingTime;
  608. _closingTime = closingTime;
  609. }
  610. /**
  611. * @return the crowdsale opening time.
  612. */
  613. function openingTime() public view returns (uint256) {
  614. return _openingTime;
  615. }
  616. /**
  617. * @return the crowdsale closing time.
  618. */
  619. function closingTime() public view returns (uint256) {
  620. return _closingTime;
  621. }
  622. /**
  623. * @return true if the crowdsale is open, false otherwise.
  624. */
  625. function isOpen() public view returns (bool) {
  626. // solhint-disable-next-line not-rely-on-time
  627. return block.timestamp >= _openingTime && block.timestamp <= _closingTime;
  628. }
  629. /**
  630. * @dev Checks whether the period in which the crowdsale is open has already elapsed.
  631. * @return Whether crowdsale period has elapsed
  632. */
  633. function hasClosed() public view returns (bool) {
  634. // solhint-disable-next-line not-rely-on-time
  635. return block.timestamp > _closingTime;
  636. }
  637. /**
  638. * @dev Extend parent behavior requiring to be within contributing period.
  639. * @param beneficiary Token purchaser
  640. * @param weiAmount Amount of wei contributed
  641. */
  642. function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal onlyWhileOpen view {
  643. super._preValidatePurchase(beneficiary, weiAmount);
  644. }
  645. /**
  646. * @dev Extend crowdsale.
  647. * @param newClosingTime Crowdsale closing time
  648. */
  649. function _extendTime(uint256 newClosingTime) internal {
  650. require(!hasClosed(), "TimedCrowdsale: already closed");
  651. // solhint-disable-next-line max-line-length
  652. require(newClosingTime > _closingTime, "TimedCrowdsale: new closing time is before current closing time");
  653. emit TimedCrowdsaleExtended(_closingTime, newClosingTime);
  654. _closingTime = newClosingTime;
  655. }
  656. }
  657. pragma solidity ^0.5.0;
  658. /**
  659. * @title IncreasingPriceCrowdsale
  660. * @dev Extension of Crowdsale contract that increases the price of tokens linearly in time.
  661. * Note that what should be provided to the constructor is the initial and final _rates_, that is,
  662. * the amount of tokens per wei contributed. Thus, the initial rate must be greater than the final rate.
  663. */
  664. contract IncreasingPriceCrowdsale is TimedCrowdsale {
  665. using SafeMath for uint256;
  666. uint256 private _initialRate;
  667. uint256 private _finalRate;
  668. /**
  669. * @dev Constructor, takes initial and final rates of tokens received per wei contributed.
  670. * @param initialRate Number of tokens a buyer gets per wei at the start of the crowdsale
  671. * @param finalRate Number of tokens a buyer gets per wei at the end of the crowdsale
  672. */
  673. constructor (uint256 initialRate, uint256 finalRate) public {
  674. require(finalRate > 0, "IncreasingPriceCrowdsale: final rate is 0");
  675. // solhint-disable-next-line max-line-length
  676. require(initialRate > finalRate, "IncreasingPriceCrowdsale: initial rate is not greater than final rate");
  677. _initialRate = initialRate;
  678. _finalRate = finalRate;
  679. }
  680. /**
  681. * The base rate function is overridden to revert, since this crowdsale doesn't use it, and
  682. * all calls to it are a mistake.
  683. */
  684. function rate() public view returns (uint256) {
  685. revert("IncreasingPriceCrowdsale: rate() called");
  686. }
  687. /**
  688. * @return the initial rate of the crowdsale.
  689. */
  690. function initialRate() public view returns (uint256) {
  691. return _initialRate;
  692. }
  693. /**
  694. * @return the final rate of the crowdsale.
  695. */
  696. function finalRate() public view returns (uint256) {
  697. return _finalRate;
  698. }
  699. /**
  700. * @dev Returns the rate of tokens per wei at the present time.
  701. * Note that, as price _increases_ with time, the rate _decreases_.
  702. * @return The number of tokens a buyer gets per wei at a given time
  703. */
  704. function getCurrentRate() public view returns (uint256) {
  705. if (!isOpen()) {
  706. return 0;
  707. }
  708. // solhint-disable-next-line not-rely-on-time
  709. uint256 elapsedTime = block.timestamp.sub(openingTime());
  710. uint256 timeRange = closingTime().sub(openingTime());
  711. uint256 rateRange = _initialRate.sub(_finalRate);
  712. return _initialRate.sub(elapsedTime.mul(rateRange).div(timeRange));
  713. }
  714. /**
  715. * @dev Overrides parent method taking into account variable rate.
  716. * @param weiAmount The value in wei to be converted into tokens
  717. * @return The number of tokens _weiAmount wei will buy at present time
  718. */
  719. function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
  720. uint256 currentRate = getCurrentRate();
  721. return currentRate.mul(weiAmount);
  722. }
  723. }
  724. contract TestToken is ERC20 {
  725. using SafeMath for uint256;
  726. string public symbol = "TEST";
  727. string public name = "TEST Token";
  728. uint8 public decimals = 18;
  729. uint256 public _totalSupply = 140000000 * 10**uint256(decimals);
  730. }
  731. contract TestCrowdsale is Crowdsale, AllowanceCrowdsale, TimedCrowdsale
  732. {
  733. constructor(
  734. uint256 _openingTime,
  735. uint256 _closingTime,
  736. uint256 _rate,
  737. address _wallet,
  738. address _tokenWallet,
  739. address _token
  740. )
  741. public
  742. AllowanceCrowdsale(_tokenWallet)
  743. TimedCrowdsale(_openingTime, _closingTime)
  744. {
  745. }
  746. }

TestCrowdsale.sol

Comments powered by Disqus