Setting crowdsale rate manually

Hi @bayram,

We shouldn't modify the OpenZeppelin Contracts themselves, we should inherit and where needed override.

https://docs.openzeppelin.com/contracts/2.x/#usage
Warning: You should always use the installed code as-is, and neither copy-paste it from online sources, nor modify it yourself.

As an aside, we don't need "../node_modules" on import statements.

import "../node_modules/@openzeppelin/contracts/crowdsale/Crowdsale.sol";

Regards state variables being private, the release notes for OpenZeppelin 2.0 explain:

https://github.com/OpenZeppelin/openzeppelin-contracts/releases/tag/v2.0.0
All state variables are now private, which means that derived contracts cannot access them directly, but have to use getters. This is to increase encapsulation, to be able to reason better about the code.

We can override Crowdsale functionality to give a changeable/settable rate so could do something like the following code.
Please note, I haven't tested this smart contract at all.

As always, I recommend that smart contracts are appropriately tested and audited.

pragma solidity ^0.5.0;

import "@openzeppelin/contracts/access/Roles.sol";
import "@openzeppelin/contracts/crowdsale/Crowdsale.sol";

contract MyCrowdsale is Crowdsale{
  using Roles for Roles.Role;

  Roles.Role private _owners;

  uint256 private _changeableRate;

  constructor(uint256 initialRate, address payable wallet, IERC20 tokenAddr, address ownerAddr)
  Crowdsale(initialRate, wallet, tokenAddr)
  public
  {
    _owners.add(ownerAddr);

    _changeableRate = initialRate;
  }

  function setRate(uint256 newRate) public
  {
    require(_owners.has(msg.sender), "DOES_NOT_HAVE_RATE_SETTER_ROLE");
    _changeableRate = newRate;
  }

  function rate() public view returns (uint256) {
    return _changeableRate;
  }

  function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
    return weiAmount.mul(_changeableRate);
  }
}
2 Likes