Skip to content

Instantly share code, notes, and snippets.

@djenning90
Created April 13, 2019 20:47
Show Gist options
  • Select an option

  • Save djenning90/c3a8a654be97afe81406e37dae7af2fe to your computer and use it in GitHub Desktop.

Select an option

Save djenning90/c3a8a654be97afe81406e37dae7af2fe to your computer and use it in GitHub Desktop.
MediaRich.io Dyncoin proxy token (DYNP)
pragma solidity ^0.5.7;
/**
* @dev Implements a contract to add password-protection support to API calls of child contracts.
* This is secure through storage of only the keccak256 hash of the password, which is irreversible.
* Critically, all sensitive methods have private visibility.
*
* Deployed to Ethereum address: 0xabfe059e98b75b9293b341d461dad649fef25cf9
*
* As implemented, the password has contract-wide scope. This does not implement per-account passwords,
* though that would not be difficult to do.
*/
contract PasswordProtected {
bytes32 private passwordHash;
/**
* A default contract password must be set at construction time.
*/
constructor (string memory password) internal {
_setNewPassword(password);
}
function _setNewPassword(string memory password) private {
passwordHash = keccak256(bytes(password));
}
function _isValidPassword(string memory password) internal view returns (bool ok) {
return (bytes32(keccak256(bytes(password))) == passwordHash);
}
/**
* Any contract functions requiring password-restricted access can use this modifier.
*/
modifier onlyValidPassword(string memory password) {
require(_isValidPassword(password), "access denied");
_;
}
/**
* Allow password to be changed.
*/
function _changePassword(string memory oldPassword, string memory newPassword) onlyValidPassword(oldPassword) internal returns (bool ok) {
_setNewPassword(newPassword);
return true;
}
}
pragma solidity ^0.5.7;
contract Identity {
mapping(address => string) private _names;
/**
* Handy function to associate a short name with the account.
*/
function iAm(string memory shortName) public {
_names[msg.sender] = shortName;
}
/**
* Handy function to confirm address of the current account.
*/
function whereAmI() public view returns (address yourAddress) {
address myself = msg.sender;
return myself;
}
/**
* Handy function to confirm short name of the current account.
*/
function whoAmI() public view returns (string memory yourName) {
return (_names[msg.sender]);
}
}
pragma solidity ^0.5.2;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.2;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error.
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity ^0.5.2;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses.
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
pragma solidity ^0.5.2;
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance.
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.2;
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
pragma solidity ^0.5.2;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.5.2;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
pragma solidity ^0.5.7;
/**
* @dev This role allows the contract to be paused, so that in case something goes horribly wrong
* during an ICO, the owner/administrator has an ability to suspend all transactions while things
* are sorted out.
*
* NOTE: We have implemented a role model only the contract owner can assign/un-assign roles.
* This is necessary to support enterprise software, which requires a permissions model in which
* roles can be owner-administered, in contrast to a blockchain community approach in which
* permissions can be self-administered. Therefore, this implementation replaces the self-service
* "renounce" approach with one where only the owner is allowed to makes role changes.
*
* Owner is not allowed to renounce ownership, lest the contract go without administration. But
* it is ok for owner to shed initially granted roles by removing role from self.
*/
contract PauserRole is Ownable {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender), "onlyPauser");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyOwner {
_addPauser(account);
}
function removePauser(address account) public onlyOwner {
_removePauser(account);
}
function _addPauser(address account) private {
require(account != address(0));
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) private {
require(account != address(0));
_pausers.remove(account);
emit PauserRemoved(account);
}
// =========================================================================
// === Overridden ERC20 functionality
// =========================================================================
/**
* Ensure there is no way for the contract to end up with no owner. That would inadvertently result in
* pauser administration becoming impossible. We override this to always disallow it.
*/
function renounceOwnership() public onlyOwner {
require(false, "forbidden");
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_removePauser(msg.sender);
super.transferOwnership(newOwner);
_addPauser(newOwner);
}
}
pragma solidity ^0.5.2;
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return True if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
pragma solidity ^0.5.2;
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
*/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
pragma solidity ^0.5.7;
contract VerifiedAccount is ERC20, Ownable {
mapping(address => bool) private _isRegistered;
constructor () internal {
// The smart contract starts off registering itself, since address is known.
registerAccount();
}
event AccountRegistered(address indexed account);
/**
* This registers the calling wallet address as a known address. Operations that transfer responsibility
* may require the target account to be a registered account, to protect the system from getting into a
* state where administration or a large amount of funds can become forever inaccessible.
*/
function registerAccount() public returns (bool ok) {
_isRegistered[msg.sender] = true;
emit AccountRegistered(msg.sender);
return true;
}
function isRegistered(address account) public view returns (bool ok) {
return _isRegistered[account];
}
function _accountExists(address account) internal view returns (bool exists) {
return account == msg.sender || _isRegistered[account];
}
modifier onlySafeAccount(address account) {
require(_accountExists(account), "account not registered");
_;
}
// =========================================================================
// === Safe ERC20 methods
// =========================================================================
function safeTransfer(address to, uint256 value) public onlySafeAccount(to) returns (bool ok) {
transfer(to, value);
return true;
}
function safeApprove(address spender, uint256 value) public onlySafeAccount(spender) returns (bool ok) {
approve(spender, value);
return true;
}
function safeTransferFrom(address from, address to, uint256 value) public onlySafeAccount(to) returns (bool ok) {
transferFrom(from, to, value);
return true;
}
// =========================================================================
// === Safe ownership transfer
// =========================================================================
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlySafeAccount(newOwner) onlyOwner {
super.transferOwnership(newOwner);
}
}
pragma solidity ^0.5.7;
/**
* @dev GrantorRole trait
*
* This adds support for a role that allows creation of vesting token grants, allocated from the
* role holder's wallet.
*
* NOTE: We have implemented a role model only the contract owner can assign/un-assign roles.
* This is necessary to support enterprise software, which requires a permissions model in which
* roles can be owner-administered, in contrast to a blockchain community approach in which
* permissions can be self-administered. Therefore, this implementation replaces the self-service
* "renounce" approach with one where only the owner is allowed to makes role changes.
*
* Owner is not allowed to renounce ownership, lest the contract go without administration. But
* it is ok for owner to shed initially granted roles by removing role from self.
*/
contract GrantorRole is Ownable {
bool private constant OWNER_UNIFORM_GRANTOR_FLAG = false;
using Roles for Roles.Role;
event GrantorAdded(address indexed account);
event GrantorRemoved(address indexed account);
Roles.Role private _grantors;
mapping(address => bool) private _isUniformGrantor;
constructor () internal {
_addGrantor(msg.sender, OWNER_UNIFORM_GRANTOR_FLAG);
}
modifier onlyGrantor() {
require(isGrantor(msg.sender), "onlyGrantor");
_;
}
modifier onlyGrantorOrSelf(address account) {
require(isGrantor(msg.sender) || msg.sender == account, "onlyGrantorOrSelf");
_;
}
function isGrantor(address account) public view returns (bool) {
return _grantors.has(account);
}
function addGrantor(address account, bool isUniformGrantor) public onlyOwner {
_addGrantor(account, isUniformGrantor);
}
function removeGrantor(address account) public onlyOwner {
_removeGrantor(account);
}
function _addGrantor(address account, bool isUniformGrantor) private {
require(account != address(0));
_grantors.add(account);
_isUniformGrantor[account] = isUniformGrantor;
emit GrantorAdded(account);
}
function _removeGrantor(address account) private {
require(account != address(0));
_grantors.remove(account);
emit GrantorRemoved(account);
}
function isUniformGrantor(address account) public view returns (bool) {
return isGrantor(account) && _isUniformGrantor[account];
}
modifier onlyUniformGrantor() {
require(isUniformGrantor(msg.sender), "Only uniform grantor role can do this.");
// Only grantor role can do this.
_;
}
// =========================================================================
// === Overridden ERC20 functionality
// =========================================================================
/**
* Ensure there is no way for the contract to end up with no owner. That would inadvertently result in
* token grant administration becoming impossible. We override this to always disallow it.
*/
function renounceOwnership() public onlyOwner {
require(false, "forbidden");
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_removeGrantor(msg.sender);
super.transferOwnership(newOwner);
_addGrantor(newOwner, OWNER_UNIFORM_GRANTOR_FLAG);
}
}
pragma solidity ^0.5.7;
interface IERC20Vestable {
function getIntrinsicVestingSchedule(address grantHolder)
external
view
returns (
uint32 cliffDuration,
uint32 vestDuration,
uint32 vestIntervalDays
);
function grantVestingTokens(
address beneficiary,
uint256 totalAmount,
uint256 vestingAmount,
uint32 startDay,
uint32 duration,
uint32 cliffDuration,
uint32 interval,
bool isRevocable
) external returns (bool ok);
function today() external view returns (uint32 dayNumber);
function vestingForAccountAsOf(
address grantHolder,
uint32 onDayOrToday
)
external
view
returns (
uint256 amountVested,
uint256 amountNotVested,
uint256 amountOfGrant,
uint32 vestStartDay,
uint32 cliffDuration,
uint32 vestDuration,
uint32 vestIntervalDays,
bool isActive,
bool wasRevoked
);
function vestingAsOf(uint32 onDayOrToday) external view returns (
uint256 amountVested,
uint256 amountNotVested,
uint256 amountOfGrant,
uint32 vestStartDay,
uint32 cliffDuration,
uint32 vestDuration,
uint32 vestIntervalDays,
bool isActive,
bool wasRevoked
);
function revokeGrant(address grantHolder, uint32 onDay) external returns (bool);
event VestingScheduleCreated(
address indexed vestingLocation,
uint32 cliffDuration, uint32 indexed duration, uint32 interval,
bool indexed isRevocable);
event VestingTokensGranted(
address indexed beneficiary,
uint256 indexed vestingAmount,
uint32 startDay,
address vestingLocation,
address indexed grantor);
event GrantRevoked(address indexed grantHolder, uint32 indexed onDay);
}
pragma solidity ^0.5.7;
/**
* @title Contract for grantable ERC20 token vesting schedules
*
* @notice Adds to an ERC20 support for grantor wallets, which are able to grant vesting tokens to
* beneficiary wallets, following per-wallet custom vesting schedules.
*
* @dev Contract which gives subclass contracts the ability to act as a pool of funds for allocating
* tokens to any number of other addresses. Token grants support the ability to vest over time in
* accordance a predefined vesting schedule. A given wallet can receive no more than one token grant.
*
* Tokens are transferred from the pool to the recipient at the time of grant, but the recipient
* will only able to transfer tokens out of their wallet after they have vested. Transfers of non-
* vested tokens are prevented.
*
* Two types of toke grants are supported:
* - Irrevocable grants, intended for use in cases when vesting tokens have been issued in exchange
* for value, such as with tokens that have been purchased in an ICO.
* - Revocable grants, intended for use in cases when vesting tokens have been gifted to the holder,
* such as with employee grants that are given as compensation.
*/
contract ERC20Vestable is ERC20, VerifiedAccount, GrantorRole, IERC20Vestable {
using SafeMath for uint256;
// Date-related constants for sanity-checking dates to reject obvious erroneous inputs
// and conversions from seconds to days and years that are more or less leap year-aware.
uint32 private constant THOUSAND_YEARS_DAYS = 365243; /* See https://www.timeanddate.com/date/durationresult.html?m1=1&d1=1&y1=2000&m2=1&d2=1&y2=3000 */
uint32 private constant TEN_YEARS_DAYS = THOUSAND_YEARS_DAYS / 100; /* Includes leap years (though it doesn't really matter) */
uint32 private constant SECONDS_PER_DAY = 24 * 60 * 60; /* 86400 seconds in a day */
uint32 private constant JAN_1_2000_SECONDS = 946684800; /* Saturday, January 1, 2000 0:00:00 (GMT) (see https://www.epochconverter.com/) */
uint32 private constant JAN_1_2000_DAYS = JAN_1_2000_SECONDS / SECONDS_PER_DAY;
uint32 private constant JAN_1_3000_DAYS = JAN_1_2000_DAYS + THOUSAND_YEARS_DAYS;
struct vestingSchedule {
bool isValid; /* true if an entry exists and is valid */
bool isRevocable; /* true if the vesting option is revocable (a gift), false if irrevocable (purchased) */
uint32 cliffDuration; /* Duration of the cliff, with respect to the grant start day, in days. */
uint32 duration; /* Duration of the vesting schedule, with respect to the grant start day, in days. */
uint32 interval; /* Duration in days of the vesting interval. */
}
struct tokenGrant {
bool isActive; /* true if this vesting entry is active and in-effect entry. */
bool wasRevoked; /* true if this vesting schedule was revoked. */
uint32 startDay; /* Start day of the grant, in days since the UNIX epoch (start of day). */
uint256 amount; /* Total number of tokens that vest. */
address vestingLocation; /* Address of wallet that is holding the vesting schedule. */
address grantor; /* Grantor that made the grant */
}
mapping(address => vestingSchedule) private _vestingSchedules;
mapping(address => tokenGrant) private _tokenGrants;
// =========================================================================
// === Methods for administratively creating a vesting schedule for an account.
// =========================================================================
/**
* @dev This one-time operation permanently establishes a vesting schedule in the given account.
*
* For standard grants, this establishes the vesting schedule in the beneficiary's account.
* For uniform grants, this establishes the vesting schedule in the linked grantor's account.
*
* @param vestingLocation = Account into which to store the vesting schedule. Can be the account
* of the beneficiary (for one-off grants) or the account of the grantor (for uniform grants
* made from grant pools).
* @param cliffDuration = Duration of the cliff, with respect to the grant start day, in days.
* @param duration = Duration of the vesting schedule, with respect to the grant start day, in days.
* @param interval = Number of days between vesting increases.
* @param isRevocable = True if the grant can be revoked (i.e. was a gift) or false if it cannot
* be revoked (i.e. tokens were purchased).
*/
function _setVestingSchedule(
address vestingLocation,
uint32 cliffDuration, uint32 duration, uint32 interval,
bool isRevocable) internal returns (bool ok) {
// Check for a valid vesting schedule given (disallow absurd values to reject likely bad input).
require(
duration > 0 && duration <= TEN_YEARS_DAYS
&& cliffDuration < duration
&& interval >= 1,
"invalid vesting schedule"
);
// Make sure the duration values are in harmony with interval (both should be an exact multiple of interval).
require(
duration % interval == 0 && cliffDuration % interval == 0,
"invalid cliff/duration for interval"
);
// Create and populate a vesting schedule.
_vestingSchedules[vestingLocation] = vestingSchedule(
true/*isValid*/,
isRevocable,
cliffDuration, duration, interval
);
// Emit the event and return success.
emit VestingScheduleCreated(
vestingLocation,
cliffDuration, duration, interval,
isRevocable);
return true;
}
function _hasVestingSchedule(address account) internal view returns (bool ok) {
return _vestingSchedules[account].isValid;
}
/**
* @dev returns all information about the vesting schedule directly associated with the given
* account. This can be used to double check that a uniform grantor has been set up with a
* correct vesting schedule. Also, recipients of standard (non-uniform) grants can use this.
* This method is only callable by the account holder or a grantor, so this is mainly intended
* for administrative use.
*
* Holders of uniform grants must use vestingAsOf() to view their vesting schedule, as it is
* stored in the grantor account.
*
* @param grantHolder = The address to do this for.
* the special value 0 to indicate today.
* @return = A tuple with the following values:
* vestDuration = grant duration in days.
* cliffDuration = duration of the cliff.
* vestIntervalDays = number of days between vesting periods.
*/
function getIntrinsicVestingSchedule(address grantHolder)
public
view
onlyGrantorOrSelf(grantHolder)
returns (
uint32 vestDuration,
uint32 cliffDuration,
uint32 vestIntervalDays
)
{
return (
_vestingSchedules[grantHolder].duration,
_vestingSchedules[grantHolder].cliffDuration,
_vestingSchedules[grantHolder].interval
);
}
// =========================================================================
// === Token grants (general-purpose)
// === Methods to be used for administratively creating one-off token grants with vesting schedules.
// =========================================================================
/**
* @dev Immediately grants tokens to an account, referencing a vesting schedule which may be
* stored in the same account (individual/one-off) or in a different account (shared/uniform).
*
* @param beneficiary = Address to which tokens will be granted.
* @param totalAmount = Total number of tokens to deposit into the account.
* @param vestingAmount = Out of totalAmount, the number of tokens subject to vesting.
* @param startDay = Start day of the grant's vesting schedule, in days since the UNIX epoch
* (start of day). The startDay may be given as a date in the future or in the past, going as far
* back as year 2000.
* @param vestingLocation = Account where the vesting schedule is held (must already exist).
* @param grantor = Account which performed the grant. Also the account from where the granted
* funds will be withdrawn.
*/
function _grantVestingTokens(
address beneficiary,
uint256 totalAmount,
uint256 vestingAmount,
uint32 startDay,
address vestingLocation,
address grantor
)
internal returns (bool ok)
{
// Make sure no prior grant is in effect.
require(!_tokenGrants[beneficiary].isActive, "grant already exists");
// Check for valid vestingAmount
require(
vestingAmount <= totalAmount && vestingAmount > 0
&& startDay >= JAN_1_2000_DAYS && startDay < JAN_1_3000_DAYS,
"invalid vesting params");
// Make sure the vesting schedule we are about to use is valid.
require(_hasVestingSchedule(vestingLocation), "no such vesting schedule");
// Transfer the total number of tokens from grantor into the account's holdings.
_transfer(grantor, beneficiary, totalAmount);
/* Emits a Transfer event. */
// Create and populate a token grant, referencing vesting schedule.
_tokenGrants[beneficiary] = tokenGrant(
true/*isActive*/,
false/*wasRevoked*/,
startDay,
vestingAmount,
vestingLocation, /* The wallet address where the vesting schedule is kept. */
grantor /* The account that performed the grant (where revoked funds would be sent) */
);
// Emit the event and return success.
emit VestingTokensGranted(beneficiary, vestingAmount, startDay, vestingLocation, grantor);
return true;
}
/**
* @dev Immediately grants tokens to an address, including a portion that will vest over time
* according to a set vesting schedule. The overall duration and cliff duration of the grant must
* be an even multiple of the vesting interval.
*
* @param beneficiary = Address to which tokens will be granted.
* @param totalAmount = Total number of tokens to deposit into the account.
* @param vestingAmount = Out of totalAmount, the number of tokens subject to vesting.
* @param startDay = Start day of the grant's vesting schedule, in days since the UNIX epoch
* (start of day). The startDay may be given as a date in the future or in the past, going as far
* back as year 2000.
* @param duration = Duration of the vesting schedule, with respect to the grant start day, in days.
* @param cliffDuration = Duration of the cliff, with respect to the grant start day, in days.
* @param interval = Number of days between vesting increases.
* @param isRevocable = True if the grant can be revoked (i.e. was a gift) or false if it cannot
* be revoked (i.e. tokens were purchased).
*/
function grantVestingTokens(
address beneficiary,
uint256 totalAmount,
uint256 vestingAmount,
uint32 startDay,
uint32 duration,
uint32 cliffDuration,
uint32 interval,
bool isRevocable
) public onlyGrantor returns (bool ok) {
// Make sure no prior vesting schedule has been set.
require(!_tokenGrants[beneficiary].isActive, "grant already exists");
// The vesting schedule is unique to this wallet and so will be stored here,
_setVestingSchedule(beneficiary, cliffDuration, duration, interval, isRevocable);
// Issue grantor tokens to the beneficiary, using beneficiary's own vesting schedule.
_grantVestingTokens(beneficiary, totalAmount, vestingAmount, startDay, beneficiary, msg.sender);
return true;
}
/**
* @dev This variant only grants tokens if the beneficiary account has previously self-registered.
*/
function safeGrantVestingTokens(
address beneficiary, uint256 totalAmount, uint256 vestingAmount,
uint32 startDay, uint32 duration, uint32 cliffDuration, uint32 interval,
bool isRevocable) public onlyGrantor onlySafeAccount(beneficiary) returns (bool ok) {
return grantVestingTokens(
beneficiary, totalAmount, vestingAmount,
startDay, duration, cliffDuration, interval,
isRevocable);
}
// =========================================================================
// === Check vesting.
// =========================================================================
/**
* @dev returns the day number of the current day, in days since the UNIX epoch.
*/
function today() public view returns (uint32 dayNumber) {
return uint32(block.timestamp / SECONDS_PER_DAY);
}
function _effectiveDay(uint32 onDayOrToday) internal view returns (uint32 dayNumber) {
return onDayOrToday == 0 ? today() : onDayOrToday;
}
/**
* @dev Determines the amount of tokens that have not vested in the given account.
*
* The math is: not vested amount = vesting amount * (end date - on date)/(end date - start date)
*
* @param grantHolder = The account to check.
* @param onDayOrToday = The day to check for, in days since the UNIX epoch. Can pass
* the special value 0 to indicate today.
*/
function _getNotVestedAmount(address grantHolder, uint32 onDayOrToday) internal view returns (uint256 amountNotVested) {
tokenGrant storage grant = _tokenGrants[grantHolder];
vestingSchedule storage vesting = _vestingSchedules[grant.vestingLocation];
uint32 onDay = _effectiveDay(onDayOrToday);
// If there's no schedule, or before the vesting cliff, then the full amount is not vested.
if (!grant.isActive || onDay < grant.startDay + vesting.cliffDuration)
{
// None are vested (all are not vested)
return grant.amount;
}
// If after end of vesting, then the not vested amount is zero (all are vested).
else if (onDay >= grant.startDay + vesting.duration)
{
// All are vested (none are not vested)
return uint256(0);
}
// Otherwise a fractional amount is vested.
else
{
// Compute the exact number of days vested.
uint32 daysVested = onDay - grant.startDay;
// Adjust result rounding down to take into consideration the interval.
uint32 effectiveDaysVested = (daysVested / vesting.interval) * vesting.interval;
// Compute the fraction vested from schedule using 224.32 fixed point math for date range ratio.
// Note: This is safe in 256-bit math because max value of X billion tokens = X*10^27 wei, and
// typical token amounts can fit into 90 bits. Scaling using a 32 bits value results in only 125
// bits before reducing back to 90 bits by dividing. There is plenty of room left, even for token
// amounts many orders of magnitude greater than mere billions.
uint256 vested = grant.amount.mul(effectiveDaysVested).div(vesting.duration);
return grant.amount.sub(vested);
}
}
/**
* @dev Computes the amount of funds in the given account which are available for use as of
* the given day. If there's no vesting schedule then 0 tokens are considered to be vested and
* this just returns the full account balance.
*
* The math is: available amount = total funds - notVestedAmount.
*
* @param grantHolder = The account to check.
* @param onDay = The day to check for, in days since the UNIX epoch.
*/
function _getAvailableAmount(address grantHolder, uint32 onDay) internal view returns (uint256 amountAvailable) {
uint256 totalTokens = balanceOf(grantHolder);
uint256 vested = totalTokens.sub(_getNotVestedAmount(grantHolder, onDay));
return vested;
}
/**
* @dev returns all information about the grant's vesting as of the given day
* for the given account. Only callable by the account holder or a grantor, so
* this is mainly intended for administrative use.
*
* @param grantHolder = The address to do this for.
* @param onDayOrToday = The day to check for, in days since the UNIX epoch. Can pass
* the special value 0 to indicate today.
* @return = A tuple with the following values:
* amountVested = the amount out of vestingAmount that is vested
* amountNotVested = the amount that is vested (equal to vestingAmount - vestedAmount)
* amountOfGrant = the amount of tokens subject to vesting.
* vestStartDay = starting day of the grant (in days since the UNIX epoch).
* vestDuration = grant duration in days.
* cliffDuration = duration of the cliff.
* vestIntervalDays = number of days between vesting periods.
* isActive = true if the vesting schedule is currently active.
* wasRevoked = true if the vesting schedule was revoked.
*/
function vestingForAccountAsOf(
address grantHolder,
uint32 onDayOrToday
)
public
view
onlyGrantorOrSelf(grantHolder)
returns (
uint256 amountVested,
uint256 amountNotVested,
uint256 amountOfGrant,
uint32 vestStartDay,
uint32 vestDuration,
uint32 cliffDuration,
uint32 vestIntervalDays,
bool isActive,
bool wasRevoked
)
{
tokenGrant storage grant = _tokenGrants[grantHolder];
vestingSchedule storage vesting = _vestingSchedules[grant.vestingLocation];
uint256 notVestedAmount = _getNotVestedAmount(grantHolder, onDayOrToday);
uint256 grantAmount = grant.amount;
return (
grantAmount.sub(notVestedAmount),
notVestedAmount,
grantAmount,
grant.startDay,
vesting.duration,
vesting.cliffDuration,
vesting.interval,
grant.isActive,
grant.wasRevoked
);
}
/**
* @dev returns all information about the grant's vesting as of the given day
* for the current account, to be called by the account holder.
*
* @param onDayOrToday = The day to check for, in days since the UNIX epoch. Can pass
* the special value 0 to indicate today.
* @return = A tuple with the following values:
* amountVested = the amount out of vestingAmount that is vested
* amountNotVested = the amount that is vested (equal to vestingAmount - vestedAmount)
* amountOfGrant = the amount of tokens subject to vesting.
* vestStartDay = starting day of the grant (in days since the UNIX epoch).
* cliffDuration = duration of the cliff.
* vestDuration = grant duration in days.
* vestIntervalDays = number of days between vesting periods.
* isActive = true if the vesting schedule is currently active.
* wasRevoked = true if the vesting schedule was revoked.
*/
function vestingAsOf(uint32 onDayOrToday) public view returns (
uint256 amountVested,
uint256 amountNotVested,
uint256 amountOfGrant,
uint32 vestStartDay,
uint32 cliffDuration,
uint32 vestDuration,
uint32 vestIntervalDays,
bool isActive,
bool wasRevoked
)
{
return vestingForAccountAsOf(msg.sender, onDayOrToday);
}
/**
* @dev returns true if the account has sufficient funds available to cover the given amount,
* including consideration for vesting tokens.
*
* @param account = The account to check.
* @param amount = The required amount of vested funds.
* @param onDay = The day to check for, in days since the UNIX epoch.
*/
function _fundsAreAvailableOn(address account, uint256 amount, uint32 onDay) internal view returns (bool ok) {
return (amount <= _getAvailableAmount(account, onDay));
}
/**
* @dev Modifier to make a function callable only when the amount is sufficiently vested right now.
*
* @param account = The account to check.
* @param amount = The required amount of vested funds.
*/
modifier onlyIfFundsAvailableNow(address account, uint256 amount) {
// Distinguish insufficient overall balance from insufficient vested funds balance in failure msg.
require(_fundsAreAvailableOn(account, amount, today()),
balanceOf(account) < amount ? "insufficient funds" : "insufficient vested funds");
_;
}
// =========================================================================
// === Grant revocation
// =========================================================================
/**
* @dev If the account has a revocable grant, this forces the grant to end based on computing
* the amount vested up to the given date. All tokens that would no longer vest are returned
* to the account of the original grantor.
*
* @param grantHolder = Address to which tokens will be granted.
* @param onDay = The date upon which the vesting schedule will be effectively terminated,
* in days since the UNIX epoch (start of day).
*/
function revokeGrant(address grantHolder, uint32 onDay) public onlyGrantor returns (bool ok) {
tokenGrant storage grant = _tokenGrants[grantHolder];
vestingSchedule storage vesting = _vestingSchedules[grant.vestingLocation];
uint256 notVestedAmount;
// Make sure grantor can only revoke from own pool.
require(msg.sender == owner() || msg.sender == grant.grantor, "not allowed");
// Make sure a vesting schedule has previously been set.
require(grant.isActive, "no active vesting schedule");
// Make sure it's revocable.
require(vesting.isRevocable, "irrevocable");
// Fail on likely erroneous input.
require(onDay <= grant.startDay + vesting.duration, "no effect");
// Don"t let grantor revoke anf portion of vested amount.
require(onDay >= today(), "cannot revoke vested holdings");
notVestedAmount = _getNotVestedAmount(grantHolder, onDay);
// Use ERC20 _approve() to forcibly approve grantor to take back not-vested tokens from grantHolder.
_approve(grantHolder, grant.grantor, notVestedAmount);
/* Emits an Approval Event. */
transferFrom(grantHolder, grant.grantor, notVestedAmount);
/* Emits a Transfer and an Approval Event. */
// Kill the grant by updating wasRevoked and isActive.
_tokenGrants[grantHolder].wasRevoked = true;
_tokenGrants[grantHolder].isActive = false;
emit GrantRevoked(grantHolder, onDay);
/* Emits the GrantRevoked event. */
return true;
}
// =========================================================================
// === Overridden ERC20 functionality
// =========================================================================
/**
* @dev Methods transfer() and approve() require an additional available funds check to
* prevent spending held but non-vested tokens. Note that transferFrom() does NOT have this
* additional check because approved funds come from an already set-aside allowance, not from the wallet.
*/
function transfer(address to, uint256 value) public onlyIfFundsAvailableNow(msg.sender, value) returns (bool ok) {
return super.transfer(to, value);
}
/**
* @dev Additional available funds check to prevent spending held but non-vested tokens.
*/
function approve(address spender, uint256 value) public onlyIfFundsAvailableNow(msg.sender, value) returns (bool ok) {
return super.approve(spender, value);
}
}
pragma solidity ^0.5.7;
/**
* @title Contract for uniform granting of vesting tokens
*
* @notice Adds methods for programmatic creation of uniform or standard token vesting grants.
*
* @dev This is primarily for use by exchanges and scripted internal employee incentive grant creation.
*/
contract UniformTokenGrantor is ERC20Vestable {
struct restrictions {
bool isValid;
uint32 minStartDay; /* The smallest value for startDay allowed in grant creation. */
uint32 maxStartDay; /* The maximum value for startDay allowed in grant creation. */
uint32 expirationDay; /* The last day this grantor may make grants. */
}
mapping(address => restrictions) private _restrictions;
// =========================================================================
// === Uniform token grant setup
// === Methods used by owner to set up uniform grants on restricted grantor
// =========================================================================
event GrantorRestrictionsSet(
address indexed grantor,
uint32 minStartDay,
uint32 maxStartDay,
uint32 expirationDay);
/**
* @dev Lets owner set or change existing specific restrictions. Restrictions must be established
* before the grantor will be allowed to issue grants.
*
* All date values are expressed as number of days since the UNIX epoch. Note that the inputs are
* themselves not very thoroughly restricted. However, this method can be called more than once
* if incorrect values need to be changed, or to extend a grantor's expiration date.
*
* @param grantor = Address which will receive the uniform grantable vesting schedule.
* @param minStartDay = The smallest value for startDay allowed in grant creation.
* @param maxStartDay = The maximum value for startDay allowed in grant creation.
* @param expirationDay = The last day this grantor may make grants.
*/
function setRestrictions(
address grantor,
uint32 minStartDay,
uint32 maxStartDay,
uint32 expirationDay
)
public
onlyOwner
onlySafeAccount(grantor)
returns (bool ok)
{
require(
isUniformGrantor(grantor)
&& maxStartDay > minStartDay
&& expirationDay > today(), "invalid params");
// We allow owner to set or change existing specific restrictions.
_restrictions[grantor] = restrictions(
true/*isValid*/,
minStartDay,
maxStartDay,
expirationDay
);
// Emit the event and return success.
emit GrantorRestrictionsSet(grantor, minStartDay, maxStartDay, expirationDay);
return true;
}
/**
* @dev Lets owner permanently establish a vesting schedule for a restricted grantor to use when
* creating uniform token grants. Grantee accounts forever refer to the grantor's account to look up
* vesting, so this method can only be used once per grantor.
*
* @param grantor = Address which will receive the uniform grantable vesting schedule.
* @param duration = Duration of the vesting schedule, with respect to the grant start day, in days.
* @param cliffDuration = Duration of the cliff, with respect to the grant start day, in days.
* @param interval = Number of days between vesting increases.
* @param isRevocable = True if the grant can be revoked (i.e. was a gift) or false if it cannot
* be revoked (i.e. tokens were purchased).
*/
function setGrantorVestingSchedule(
address grantor,
uint32 duration,
uint32 cliffDuration,
uint32 interval,
bool isRevocable
)
public
onlyOwner
onlySafeAccount(grantor)
returns (bool ok)
{
// Only allow doing this to restricted grantor role account.
require(isUniformGrantor(grantor), "uniform grantor only");
// Make sure no prior vesting schedule has been set!
require(!_hasVestingSchedule(grantor), "schedule already exists");
// The vesting schedule is unique to this grantor wallet and so will be stored here to be
// referenced by future grants. Emits VestingScheduleCreated event.
_setVestingSchedule(grantor, cliffDuration, duration, interval, isRevocable);
return true;
}
// =========================================================================
// === Uniform token grants
// === Methods to be used by exchanges to use for creating tokens.
// =========================================================================
function isUniformGrantorWithSchedule(address account) internal view returns (bool ok) {
// Check for grantor that has a uniform vesting schedule already set.
return isUniformGrantor(account) && _hasVestingSchedule(account);
}
modifier onlyUniformGrantorWithSchedule(address account) {
require(isUniformGrantorWithSchedule(account), "grantor account not ready");
_;
}
modifier whenGrantorRestrictionsMet(uint32 startDay) {
restrictions storage restriction = _restrictions[msg.sender];
require(restriction.isValid, "set restrictions first");
require(
startDay >= restriction.minStartDay
&& startDay < restriction.maxStartDay, "startDay too early");
require(today() < restriction.expirationDay, "grantor expired");
_;
}
/**
* @dev Immediately grants tokens to an address, including a portion that will vest over time
* according to the uniform vesting schedule already established in the grantor's account.
*
* @param beneficiary = Address to which tokens will be granted.
* @param totalAmount = Total number of tokens to deposit into the account.
* @param vestingAmount = Out of totalAmount, the number of tokens subject to vesting.
* @param startDay = Start day of the grant's vesting schedule, in days since the UNIX epoch
* (start of day). The startDay may be given as a date in the future or in the past, going as far
* back as year 2000.
*/
function grantUniformVestingTokens(
address beneficiary,
uint256 totalAmount,
uint256 vestingAmount,
uint32 startDay
)
public
onlyUniformGrantorWithSchedule(msg.sender)
whenGrantorRestrictionsMet(startDay)
returns (bool ok)
{
// Issue grantor tokens to the beneficiary, using beneficiary's own vesting schedule.
// Emits VestingTokensGranted event.
return _grantVestingTokens(beneficiary, totalAmount, vestingAmount, startDay, msg.sender, msg.sender);
}
/**
* @dev This variant only grants tokens if the beneficiary account has previously self-registered.
*/
function safeGrantUniformVestingTokens(
address beneficiary,
uint256 totalAmount,
uint256 vestingAmount,
uint32 startDay
)
public
onlyUniformGrantorWithSchedule(msg.sender)
whenGrantorRestrictionsMet(startDay)
onlySafeAccount(beneficiary)
returns (bool ok)
{
// Issue grantor tokens to the beneficiary, using beneficiary's own vesting schedule.
// Emits VestingTokensGranted event.
return _grantVestingTokens(beneficiary, totalAmount, vestingAmount, startDay, msg.sender, msg.sender);
}
}
pragma solidity ^0.5.7;
/**
* @dev An ERC20 implementation of the Dyncoin Proxy Token. All tokens are initially pre-assigned to
* the creator, and can later be distributed freely using transfer transferFrom and other ERC20
* functions.
*/
contract ProxyToken is PasswordProtected, Identity, ERC20, ERC20Pausable, ERC20Burnable, ERC20Detailed, UniformTokenGrantor {
uint32 public constant VERSION = 5;
uint8 private constant DECIMALS = 18;
uint256 private constant TOKEN_WEI = 10 ** uint256(DECIMALS);
uint256 private constant INITIAL_WHOLE_TOKENS = uint256(5 * (10 ** 9));
uint256 private constant INITIAL_SUPPLY = uint256(INITIAL_WHOLE_TOKENS) * uint256(TOKEN_WEI);
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
constructor (string memory defaultPassword) ERC20Detailed("MediaRich.io Dyncoin proxy token", "DYNP", DECIMALS) PasswordProtected(defaultPassword) public {
// This is the only place where we ever mint tokens.
_mint(msg.sender, INITIAL_SUPPLY);
}
event DepositReceived(address indexed from, uint256 value);
/**
* fallback function: collect any ether sent to us (whether we asked for it or not).
*/
function() payable external {
// Track where unexpected ETH came from so we can follow up later.
emit DepositReceived(msg.sender, msg.value);
}
/**
* @dev Allow only the owner to burn tokens from the owner's wallet, also decreasing the total
* supply. There is no reason for a token holder to EVER call this method directly. It will be
* used by the future Dyncoin contract to implement the ProxyToken side of of token redemption.
*/
function burn(uint256 value) onlyIfFundsAvailableNow(msg.sender, value) public {
// This is the only place where we ever burn tokens.
_burn(msg.sender, value);
}
/**
* Allow owner to change password.
*/
function changePassword(string memory oldPassword, string memory newPassword) onlyOwner public returns (bool ok) {
_changePassword(oldPassword, newPassword);
return true;
}
/**
* @dev Allow pauser to kill the contract (which must already be paused), with enough restrictions
* in place to ensure this could not happen by accident very easily. ETH is returned to owner wallet.
*/
function kill(string memory password) whenPaused onlyPauser onlyValidPassword(password) public returns (bool itsDeadJim) {
require(isPauser(msg.sender), "onlyPauser");
address payable payableOwner = address(uint160(owner()));
selfdestruct(payableOwner);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment